0

Why does this come back with an error:

jQuery('#the_form').submit(function() {
    jQuery.ajax({
        url: 'stats.php?increment=true',
        success: function() {
            alert('Load was performed.');
        },
        error: function() {
            alert('Load wasnt performed.');
        }
    });

    return true;
});

and this doesn't (return is false, all else is same):

jQuery('#the_form').submit(function() {
    jQuery.ajax({
        url: 'stats.php?increment=true',
        success: function() {
            alert('Load was performed.');
        },
        error: function() {
            alert('Load wasnt performed.');
        }
    });

    return false;
});

and how do I call that script before submission (to an external action)?

0

2 Answers 2

4

You have subscribed to the .submit event of a form. In the first case you are returning true meaning that you are leaving the default action to run which is to submit the form to the server and redirect the browser to stats.php. Because the browser redirects immediately your AJAX call might never have the time to finish.

In the second case you are returning false meaning that you are canceling the default form submission and you are sending an AJAX request instead which has enough time to execute.

Sign up to request clarification or add additional context in comments.

4 Comments

To expound on that: how do I do the ajax and THEN submit?
@James Thompson, the whole point of AJAX is that it is asynchronous. If you have a situation in which you have to wait for an AJAX call to finish in order to submit a form you would be better off leaving the form submit normally and do whatever you intended to do during the AJAX call inside the script that you are posting the form to.
The form that it's posting to isn't mine.
@James Thompson, I see. In this case you may try performing a synchronous AJAX request by adding the async: false property to the $.ajax function which will block the caller until the request completes and then you can return true from the function to pursue with normal submission.
0

Well, when you submit the form, if you return true inside your .submit() method, it will make the browser actually submit the data rather than just do the AJAX call. Since you're using AJAX, you should be blocking the submit of the form because you're expecting your AJAX call to return.

1 Comment

So what do I do to submit after the ajax? Or do I have to handle the submit as part of it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.