1

I think I'm doing a classical ajax script which should be fairly easy for the people who have worked with it.

Alright the idea is to call a page from jquery ajax which calculates and loops through some data. I want the page to respond back to the javascript whenever it got 1 row calculated. The jquery should then populate a div row for row. Meaning it should NOT wait for all rows to complete, but just take one row at a time.

Does it make sense? The problem should be well-known, but sorry for my bad explanation. My code so far:

Jquery page:

$(document).ready(function() {
    loadCityFriends();
});

function loadCityFriends() {
    $.ajax({
        url: 'cityfriends.php',
        success: function(data) {
            $("#cityfriends").append(data);
        }
    });
}

And cityfriends.php (the page calculating):

foreach bla bla bla
print '{"fbid": "'.$friend["id"].'", "img": "'.$friend["picture"].'"}';

My code wait until cityfriends.php are done looping and then populates the div.

1 Answer 1

1

The only way to do this would be to make multiple independent calls to the PHP script probably first requesting the number of rows then afterwards requesting each row sequentially. PHP won't return before it's finished executing so with one ajax call you'd be looking at either all of the rows returned after calculation or just the first one.

Something like this would work:

PHP

function getRows()
{
   $query = mysql_query("SELECT * FROM `foo`");
   echo json_encode(array ("num_rows" => mysql_num_rows()) );
}

function returnRow()
{
    $row_id = $_POST["row_id"];
    $query = mysql_query("SELECT * FROM `foo` WHERE `id`=".$row_id);
    $row = mysql_fetch_array($query);

    echo json_encode(array ("row" => $row));
}

Then use ajax to first poll getRows() and then poll returnRow the appropriate number of rows returned by getRows();

Obviously you'll need to sanitize inputs and optimize the code but that should be the general idea.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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