Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Ajax: redirect to other pages without wait the result

Tags:

jquery

http

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?

like image 603
Kelvin Avatar asked Feb 02 '10 13:02

Kelvin


3 Answers

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?

like image 148
tambler Avatar answered Oct 19 '22 10:10

tambler


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.

like image 2
Emil Ivanov Avatar answered Oct 19 '22 11:10

Emil Ivanov


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.

like image 1
Sampson Avatar answered Oct 19 '22 09:10

Sampson