0

I'm trying to output echo statements in my PHP script which when launched normally via browser works fine. But when the PHP page is loaded via jQuery .load() method, the output is always buffered irrespective of whatever I do.

PHP (test.php)

header('Content-type: text/html; charset=utf-8');
header('Surrogate-Control: BigPipe/1.0');
header("Cache-Control: no-cache, must-revalidate");
header('X-Accel-Buffering: no');

ob_end_flush();
ob_implicit_flush();

echo "First line<br>";
sleep(5);
echo "Second line<br>";

So, when I launch test.php in my browser, I get the first line followed by the second line after 5 seconds (as expected). However, when I load this script into another HTML in a <div> tag, both the echo statements output at the same time i.e. after 5 seconds. Browser Chrome 64.0.3282.186.

HTML:

<div id="testDiv"></div>

JS:

<script>
    $("#testDiv").load("test.php");
</script>
10
  • 1
    PHP's output is the same in both scenarios. I'd say the jquery is the one causing this - by waiting for the complete result. But what do you think should happen instead? Do you expect the first call of load() to show the first line and the second call - after a while - to show both lines? ... or what exactly do you expect? Commented Mar 10, 2018 at 12:30
  • Anyway, here's an answer that might help you out a bit: stackoverflow.com/a/42839768/1285669 Commented Mar 10, 2018 at 12:32
  • @Smuuf I'm only loading the PHP script once. The expected output is the first echo prints the first line of text in the <div> in which it is loaded, and then after 5 seconds delay print the second line of text. Yes, jQuery's load() method somehow is waiting for the entire output to be received to flush the output into the <div> in which the PHP script is loaded. Any idea how to tell jQuery load() method to display the content as and when received instead of buffering it? Commented Mar 10, 2018 at 13:15
  • Hi. What is the main purpose of this scenario? Are you trying to create an animated HTML? Use javascript directly, not php. Or are you trying to show progress of a server script? Use javascript to call the server every x seconds to check the progress. Commented Mar 10, 2018 at 13:18
  • 1
    Or use js EventSource instead of jquery load? Commented Mar 10, 2018 at 13:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.