How do you close an ajax request from php before the script ends? Example: user requests php.php, which has the line: echo "phpphp", and after this line, the ajax request finishes and has the data "phpphp", but the PHP script keeps on running, without using processes or forking?
3 Answers
How do i implement this scenario using PHP? has the answer. Set Connection close and Content length headers, with the flushing.
ob_start();
echo "111";
header("Content-Length: ".ob_get_length());
header("Connection: close");
flush();
somescript();
2 Comments
Umair Khan
This doesnt solve it for me. In the scenario where the browser has to update the page using another request(for example Yii's CGridView), the browser's next request has to wait until the whole script has finished execution. It doesnt matter which url is requested in the second request. (WAMP, Windows 7)
om_deshpande
This doesn't work for AJAX requests. An AJAX requests read the responseText only when the readyState changes to '4'. Although the response headers will be sent once you flush, you will notice that the responseText is only detected once the backend script stops executing.
Try streaming the PHP file, and once it hits a certain point, send a return to JS and that will close the JS connection and (perhaps?) allow this php file to continue?
Haven't tried it but it's worth a shot.
// set as plain text
header('content-type:text/plain');
// let it stream
ob_implicit_flush(true);
ob_end_flush();
Comments
exit or any alias of exit will stop script execution.
Take a look at output buffering - using ob_start() with ob_flush() or simply flush() might do the trick.
1 Comment
John Smith
This works without using the ajax, on a windows installation, but it doesnt work when the ajax requests the script
die()to return the data or after echoing them?