How can I use Jquery to get PHP data step by step?

515 Views Asked by At

I'm having a little problem with jquery with php combination. Let me begin with the codes.

PHP Code :

if ($_POST["request"]==10)
    progress();

function progress()
{
    $files = getfiles();
    $progress = 0;
    $progressRate = 100/$files->number;
    for ($i=0;$i<$files->number;$i++)
    {
        sendfile($files->location[$i]);
        $progress+=$progressRate;
        echo $progress;
    }
}

Code Output : For example files->number = 2 then output will be 50 100.

Jquery Code :

jQuery.post("functions.php",{request:10},function(data){

            alert(data);


   });

Problem : What I want is to alert 50 first, then alert 100 after, I mean when the first loop ends in php and echos the first progress value, then jquery should be able to intercept it, but jquery alerts the data after the whole loop finishes, which means I get 50100 in one single alert, is there any way jQuery can handle this? I know there are other solutions using PHP and generating for example the number of loops in a hidden div or an attribute, then using loops inside the jQuery, But I really want to do it directly.

2

There are 2 best solutions below

4
On

That's not how AJAX works. It makes a single request and does "something" with the response, just like the browser does when you navigate to a URL.

The PHP script will execute server-side, print the results to the "screen" and send them back as a response.

If you want multiple variables returned, you should return them as JSON data and parse the JSON string in javascript.

3
On

jQuery (actually AJAX by default) only returns the response once the server has completed the request.

So there is no way in doing a single request to a php page and getting multiple responses. One way is to use php with the upload progress support, but I doubt that will actually help in your situation as it is only for uploading files.