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
When I pushed object into array for loop, my array was undefined
But when i pushed normally, my array got an object
I think there is a problem in the loop :((
You shouldn’t define
dataType
ashtml
in yourAjax
request, because you send JSON data. You also don’t have to specifycontentType
.try with this :