skip to Main Content

When I selected a service from select input, I got a div created by JS as below:

<form method="POST" action="/booking/success">
// SOME CODE IN HERE.................................
<div class="col-12">
      <h3 class="service__title" name="serviceTitle">Service 1</h3>
      <p><span class="display__number">1</span> x <span>500</span></p>
      <p><b class="display__total">500</b></p>
</div>
<div class="col-12">
      <h3 class="service__title" name="serviceTitle">Service 2</h3>
      <p><span class="display__number">1</span> x <span>1500</span></p>
      <p><b class="display__total">1500</b></p>
</div>
<button type="submit" class="btn btn-right" id="submitBtn" ><span>SUBMIT  </span><i class="fas fa-paper-plane"></i></button>
</form>

I create Ajax variable for using in Nodejs:

<script>
  <script>
    $("button[type='submit']").click(function (){
        var length = $('.service__title').length;
        var data = [];
        alert($('.service__title:eq(0)').text());
        alert(parseInt($('.display__number:eq(0)').text()));
        for(let i = 0; i < length; i++){
            data.push({
                title: $('.service__title:eq(i)').text(),
                quantity: parseInt($('.display__number:eq(i)').text()),
                subtotal: parseInt($('.display__total:eq(i)').text())
            })
        }
        $.ajax({
            async:false,
            url: "../booking/success",
            type: "POST",
            dataType: "html",
            data: {data:data},
            contentType: "application/x-www-form-urlencoded",
        })
            
    });

</script>

and console log:

app.post('/booking/success', async (req,res)=> {
    console.log(req.body);
    console.log(req.body.data);
    res.render("success");
})

When I clicked Submit, my array "data" is undefined.

{ data: 
[ { title: '  ', quantity: 'NaN', subtotal: 'NaN' } ] 
[ { title: '  ', quantity: 'NaN', subtotal: 'NaN' } ]

Please help me!

2

Answers



  1. You shouldn’t define dataType as html in your Ajax request, because you send JSON data. You also don’t have to specify contentType.

    try with this :

      $.ajax({
          async:false,
          url: "../booking/success",
          type: "POST",
          data: {data:data},
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search