Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue process after responding to ajax request in PHP?

Tags:

ajax

php

timeout

Some operations take too much time, which lead the ajax request to time out.

How do I finish responding to the request first, then continue that operation?

like image 541
Mask Avatar asked Sep 26 '09 13:09

Mask


2 Answers

The ignore_user_abort directive, and ignore_user_abort function are probably what you are looking for : it should allow you to send the response to the browser, and, after that, still run some calculations on your server.

This article about it might interest you : How to Use ignore_user_abort() to Do Processing Out of Band ; quoting :
EDIT 2010-03-22 : removed the link (was pointing to http:// ! waynepan.com/2007/10/11/ ! how-to-use-ignore_user_abort-to-do-process-out-of-band/ -- remove the spaces and ! if you want to try ), after seeing the comment of @Joel.

Basically, when you use ignore_user_abort(true) in your php script, the script will continue running even if the user pressed the esc or stop on his browser. How do you use this?
One use would be to return content to the user and allow the connection to be closed while processing things that don’t require user interaction.

The following example sends out $response to the user, closing the connection (making the browser’s spinner/loading bar stop), and then executes do_function_that_takes_five_mins();

And the given example :

ignore_user_abort(true);
header("Connection: close");
header("Content-Length: " . mb_strlen($response));
echo $response;
flush();
do_function_that_takes_five_mins();

(There's more I didn't copy-paste)


Note that your PHP script still has to fit in the max_execution_time and memory_limit constraints -- which means you shouldn't use this for manipulations that take too much time.

This will also use one Apache process -- which means you should not have dozens of pages that do that at the same time.

Still, nice trick to enhance use experience, I suppose ;-)

like image 75
Pascal MARTIN Avatar answered Oct 10 '22 10:10

Pascal MARTIN


Spawn a background process and return background process id so user can check on it later via some secret URL.

like image 26
Eimantas Avatar answered Oct 10 '22 10:10

Eimantas