In my php script I want to output data to the browser then sleep() for 2 seconds before running a function. The below doesnt seem to output the json before sleeping, anyone got any ideas?
if ($_POST['process'] == '1') {
// adding stuff to $data here
}
echo json_encode($data);
ob_flush();
flush();
sleep(2);
// Do something else
}
Yep, this is how you do it. Basically, you close the connection and return the response to the user while apache continues to process the file…
Works great for quick ajax calls that need an immediate response and/or take a long time to actually do the work.
I must warn you to use this type of thing sparingly… Each time this happens a new process/thread is opened up to handle the remainder of your request. Do too many too fast and you’ll run out of processes. (Depending on your setup)