简体   繁体   中英

e.preventDefault() not working when used with bootbox and jQuery.post()

What i'm trying to achieve?

I have a div that is controlled by JS that has its height changed when a menu item is clicked. So when a menu item is clicked a div appears, when it is clicked again it disappears.

Within this div i have a form, when the form is submitted a message will display asking the user if they are sure they want to submit form. If they answer yes, the form submits and an email is sent.

If the user says no the message will disappear allowing the user to make changes.

Problem

When a form is submitted the page refreshes due to the post. Thus making the div disappear.

My solution?

When the user says yes the form is posted using a jQuery.post() along with a e.preventDefault().

This should then

  1. Stop the form from refreshing (thus the div with the form is open still)
  2. Post the form data

Code

     $('#form1').submit(function(e) {
            var currentForm = this;
            e.preventDefault();
             console.log("prevent default1");//Debug Line
            bootbox.confirm("Are you sure?", function(result) {
                if (result) {
                    e.preventDefault();
                    console.log("prevent default2");//Debug Line
                      $.ajax({
               type: 'POST',
               url: 'indextest2.php',
               data: $("#form1").serialize(),
               error: function () {
                   console.log('Ajax Error');//Debug Line
               }, 
               success: function (response) {
                    console.log('Ajax Success'); //Debug Line
                        }
                    });
                }
            }); 
        }); 

What is happening?

The form is still posting causing a refresh when the user says "yes" to the message.

I think that you can put return false; just after the $.post call (and not after e.preventDefault() (this is for bootbox to wait post result) AND a return false; just after the bootbox.confirm clause (for the form not to be submiting). You can call on your success method a bootbox.hideAll to close bootbox after post.

Please put return false; after e.preventDefault();

e.preventDefault();
return false;

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