Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery ajax call only work when I'm debugging in Chrome?

Tags:

jquery

ajax

I have a simple ajax call from a form submit. It works when I debug, i.e the alert pops up but when running it, it doesn't work?

This seems a bit mysterious to me.

$(function(){

    $("#signUpForm").submit(function(){
        var request = $.ajax({
            url:"php/newUser.php",
            type:"POST"

        });

        request.done(function(msg){
            alert(msg);
        });


    });
});
like image 824
eikiro-000 Avatar asked Oct 21 '25 14:10

eikiro-000


1 Answers

If you run an ajax call on the .submit() handler of a form, the Ajax request will fire but then the form will continue submitting, thus refreshing the page and never firing your callback function.

Instead, you should call event.preventDefault() at the end of the submit handler function to prevent the browser from submitting the form normally with a new HTTP request. To do this you'll need to add event as a parameter to the callback function, like this:

$( "#target" ).submit(function( event ) {
  alert( "Handler for .submit() called." );
  event.preventDefault();
});

The reason it works when you debug is because everything happens slowly as you step through, without the browser submitting the form.

like image 95
Michael Butler Avatar answered Oct 23 '25 03:10

Michael Butler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!