views:

389

answers:

3

After clicking on a button I want to fire an Ajax call and then redirect to other pages without waiting the ajax result. Is it possible? My code as follow:

$('button').click(function(){
    $.get('mailer.php', function(){
        window.location.replace("result.php");
    });
});

The code above will wait for the ajax result before redirection. Can I just let the ajax run at the back and move on to other pages?

+2  A: 

If you move to another page the connection to the server might be dropped (there is no rule preventing the browser from doing so) and the action may not be completed. In short: you have to wait.

Emil Ivanov
I agree. What happens if there's an error in the AJAX request and the form/data needs to be sent again? You'd be best off to wait for the result, and then redirect to the other page, based on the response from the AJAX request.
S Pangborn
+1  A: 

If you leave immediately, the request will be abandoned. You would need to include logic on the server to keep whatever process going that was started by the jquery ajax request.

For example, in PHP there exists the ignore_user_abort() function, which, when set to true, will continue a process even after the user has aborted the request.

Jonathan Sampson
What if the browser doesn't even make the request, because the location has changed? There is no guarantee that it will initiate the request. What if only half of it (the first 2 headers for exaple) are sent because of latency?
Emil Ivanov
According to the OP, the request is made *before* changing the location.
Jonathan Sampson
+2  A: 

It looks like the script you're AJAX-ing to is sending an e-mail. I can see how waiting for that to complete would result in a lag on the user's end. Here's how I typically solve this problem:

Instead of having your mailer.php script immediately send the e-mail, store the message data in your db. Don't send the e-mail during the AJAX call. This will result in a very fast process for the user.

Then, you can setup a CRON job that points to a script you have specially created for sending out e-mails that have been stored in the DB.

Make sense?

tambler
thanks! Corn job seems a better way of handling my situation :)
Kelvin