1

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>

3 Answers3

0

add

  return false; 

in the end of your function in js code..this will stop the normal page relaoding and form submission. Try it and tell me

Zaki Mustafa
  • 147
  • 1
  • 11
  • Hello, Tried it but not working. Only difference it is making is it is not redirecting to localhost:3000/submittedData, but it is staying at localhost:3000 and trying to refresh the page or something. But main thing is that I am not being able to post request from that same page. :( – Arindam Saha Oct 22 '16 at 17:05
0

The problem is solved now. And the answer is well.. crazy. And I couldn't find out the root cause though. I was writing the js code in a separate file and referencing it (properly), like we usually do. But although the post was happening the page was reloading.

I copied and pasted the js code in the html page itself inside script tags and boom!! it works..

0

You should use form.on("submit") event , in your case even if you successfully canceled the click button event if the user hit the enter button while typing in one of the input fields your Ajax code will not work

Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76