简体   繁体   中英

Page reloading inspite of using preventDefault() function

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>

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

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..

您应该使用form.on("submit")事件,在您的情况下即使您成功取消了单击按钮事件,如果用户在键入输入字段时按下输入按钮,您的Ajax代码将无法工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM