user969068
user969068

Reputation: 2943

ajax call while updating page

I have an ajax call to one php script via jquery but it takes a lot of time to return results , So I would like to know how can I display results as its are being printed on my script. here just example of my php script:

<?php 
// process.php
for($i = 0; $i <= 4; $i++){
echo json_encode(array("name" => $i) );
sleep(2); // this sleeps for 2 seconds
}
?>

Now with my jquery i am calling that page and have a form with id ajaxquery on page:

$("#ajaxquery").live( "submit" , function(){
    var formdata = $(this).serialize(); 
    $.ajax
        ({
            type: "POST",
            url: "process.php",
            data: formdata,
            dataType: "json",
            success: function(data)
            {
                $("#success").html(data.name);
            }
        });

    return false; 
}); 

now this will output all results at same time after few seconds in div#success but how can i achieve it print that echo statements as soon process.php process it and then again wait 2 seconds and add next result in div success. thanks for any help.

Upvotes: 1

Views: 124

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

The success function is called only when the $.ajax function gets a successful response from the server and that happens only when the PHP script finishes it's execution. You must change your logic, for example by making another ajax call after the first one finishes that "resume" the work server side

Upvotes: 0

Jan
Jan

Reputation: 16032

You will have to setup a javascript timer on the client and call you php script every two seconds to get the new data. That data you can append for example with the jquery .append function.

Upvotes: 1

Related Questions