Question

I dont really know how to ask this which is why I am asking it here. So if I was using some code like this:

$.post("/data/something.php", {stuff: 'hi'}, function(data){
$('#box').html(data);
});

Normally if you have php like this you only get 1 result:

<?php echo $_REQUEST['stuff'] ?>

I was wondering if there is any way for the php to send a bit of data, then a little bit more later without it just sending all of it at once like so:

<?php 
echo 'Foo';
//Do stuff that takes time
echo 'Bah';
?>
Was it helpful?

Solution

There are 2 ways to accomplish this.

The first uses a standard workflow with the flush command (http://php.net/manual/en/function.flush.php). This means that you can do:

echo "Starting...\n"
flush();
// do long task
echo "Done!\n"

HOWEVER: This often won't work. For example, if your server uses deflate, the Starting likely won't get sent until the request is finished. Many other factors can cause this too (proxies, browser behaviour).

The better option is to use a polling mechanism. Your main script would write its progress to a file (with some session ID related filename), then delete that file when done. You would then add a second script to report the progress in this file (or completion if the file has been deleted) and your JavaScript would send an AJAX request to this checker script (maybe every second or two).

OTHER TIPS

In PHP

<?php 
    echo 'Foo';
    echo '||||';
    echo 'Bah';
?>

In Javascript

var responses = data.split('||||');

//you will get 
//Foo in responses[0]
//Bar in responses[1]

I expect that php has no problem doing that (as detailed by @Dave). The complicated part, is for javascript to retrieve the first part of the data, before the transmission completes...

I think what you are asking is answered here: Is it possible for an AJAX request to be read before the response is complete?

The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.

and...

So finally, yes it is possible, no it is not easy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top