I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.
I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?
<?php
echo( "We'll email you as soon as this is done." );
header( "Connection: Close" );
// do some stuff that will take a while
mail( 'dude@thatplace.com', "okay I'm done", 'Yup, all done.' );
?>
The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script:
Supposedly it requires a bit more than sending a close header.
OP then confirms: yup, this did the trick: pointing to user-note #71172 (Nov 2006) copied here:
Later on in July 2010 in a related answer Arctic Fire then linked two further user-notes that were-follow-ups to the one above:
Assuming you have a Linux server and root access, try this. It is the simplest solution I have found.
Create a new directory for the following files and give it full permissions. (We can make it more secure later.)
Put this in a file called
bgping
.Note the
&
. The ping command will run in the background while the current process moves on to the echo command. It will ping www.google.com 15 times, which will take about 15 seconds.Make it executable.
Put this in a file called
bgtest.php
.When you request bgtest.php in your browser, you should get the following response quickly, without waiting about 15 seconds for the ping command to complete.
The ping command should now be running on the server. Instead of the ping command, you could run a PHP script:
Hope this helps!
this worked for me
I'm on a shared host and
fastcgi_finish_request
is setup to exit scripts completely. I don't like theconnection: close
solution either. Using it forces a separate connection for subsequent requests, costing additional server resources. I read theTransfer-Encoding: cunked
Wikipedia Article and learned that0\r\n\r\n
terminates a response. I haven't thoroughly tested this across browsers versions and devices, but it works on all 4 of my current browsers.An alternative solution is to add the job to a queue and make a cron script which checks for new jobs and runs them.
I had to do it that way recently to circumvent limits imposed by a shared host - exec() et al was disabled for PHP run by the webserver but could run in a shell script.
Complete version: