简体   繁体   中英

Why is my page reloading even though I have event.preventDefault (form handling jquery + node.js)

I am using jQuery to asynchronously post my data to my db using node.js and express.js

Here is roughly what I am doing:

index.html:

<form id='mailer' action='/mail/new' method='post'>
  <input name='mycontent'/>
  <input type='submit'/>
</form>

script.js:

$("#mailer").submit(function(e){
  e.preventDefault();
  $.post('/mailer/new',{mycontent:mycontent});
});

app.js:

app.post("/mailer/new",function(){
  //insert into database
}

So it is essentially submitting to my database but ignoring the e.preventDefault because my page shows the loader wheel when I press submit

  1. As a commenter pointed out, you need to remove the hash # from the id attribute of your form:

    <form id='mailer'...

  2. You need quotes around the element you're submitting. A JavaScript error occurs ( undefined variable, most likely) and the form submits anyway before the preventDefault() runs.

    $(#mailer).submit(function(e){...

    Should be:

    $('#mailer').submit(function(e){

Found the answer by console logging the event object. Turns out the event object (atleast while using jquery) doesn't have a 'preventDefault' function. But rather has an 'isPreventDefault()' function which takes in true or false.

I just replaced the e.preventDefault with e.isPreventDefault(true) and this fixed it and it is not reloading now

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