I am using jquery ajax to post a form to my node.js server. I am trying to prevent the page from refreshing ( since trying to develop a SPA) using preventDefault function, but surprisingly it is redirecting. And moreover, the data is being passed to the node express server very smoothly. But somehow it is skipping a couple of line it seems. When I'm trying this in a basic POC, everything is working fine and it is preventing page refresh.
$(document).ready(function(){
$('#submit').click(function(event){
//$("form#foodForm").submit(function(event) {
window.alert( event.isDefaultPrevented() );
event.preventDefault();
window.alert( event.isDefaultPrevented() );
console.log("form submitted");
// Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
$.post(
'/submittedData', // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) {
console.log(data); /** code to handle response **/ },
"json" // The format the response should be in
);
});
});
app.js code:
app.post('/submittedData',function(req,res){
console.log('body: ' + JSON.stringify(req.body));
});
HTML piece:
<form id="foodForm" action="/submittedData" method="post">
<ul> Main course
<li> <input type="checkbox" name="items[]" value="roti">Roti </li>
<li><input type="checkbox" name="items[]" value="biryani">Biryani</li>
<li><input type="checkbox" name="items[]" value="rice">Rice</li>
</ul>
<ul> On the side
<li><input type="checkbox" name="items[]" value="chicken">Chicken</li>
<li><input type="checkbox" name="items[]" value="mutton">Mutton</li>
</ul>
<button id="submit">Submit</button>
<!-- <input type="submit" value="submit" id="submit" > -->
</form>