<?php
ob_start();
echo 'test';
ob_end_flush();
flush();
sleep(10);
I tried to output response for ajax request before the connection finishes,but not working--it will wait 10 seconds before successfully fetching response.Is it the problem of http server,in my case Apache?If that's true,how to fix it so that it echos back the response right away?
While
flush()
,ob_end_flush()
andob_flush()
is supposed to guarantee that output is sent to the server, I've found that PHP is sometimes not very forgiving of particular software configuration.On Windows especially, output buffering can be a pain to setup and the only way I've found that works reliably between systems is to reset output buffering on every flush like so:
Is it an ugly solution? Yes it is. But until all the bugs related to output buffering are fixed, I don't see this work-around going away in production code any time soon.
Also note that some anti-virus software (Panda AV and others) and proxies will hold all data until the socket is closed. You cannot guaranty that all clients will receive proper flushed data.
The simplest way to know if something is a server or browser/library issue is to monitor the request live. The 2 simplest ways of doing this in your case are:
If you see the data coming back right away but taking 10sec to display, your browser or AJAX library is waiting for the connection to close before processing the response. If it takes 10sec before you are getting anything back, your server or PHP module is at fault here.