0
$res = mysql_query("SELECT * FROM `basket` WHERE `account_id` = '$_SESSION[ID]'");
while($row = mysql_fetch_assoc($res)) {
        $search = $row['number'];
        echo $search;
}

What I'm attempting to do is use an Ajax call to this PHP file, and then the "echoed" data i want to parse and place inside a div, here's the Ajax call

$(document).ready(function() {
    var data = "func=basket";             
    $.ajax({
        url: "functions/ajax.php",
        data: data,
        type: "GET",
        success: function(data, textStatus, jqXHR){
            $("#response").html(data);
        },
        error: function (jqXHR, textStatus, errorThrown){
            console.log('Error ' + jqXHR);
        }
    });
});

But the problem I'm having is that it's not parsing the data until EVERY while($row etc.. is processed, i want to return echo row 1 by 1, how would i go about doing that

Curtis Crewe
  • 4,126
  • 5
  • 26
  • 31
  • 1
    possible duplicate of [jquery ajax, read the stream incrementally?](http://stackoverflow.com/questions/7740646/jquery-ajax-read-the-stream-incrementally) – Marc B Mar 11 '13 at 17:19
  • Something like `yield` would be perfect here ;) - you can use [flush](http://php.net/flush), though. I'll make an answer. – Jordan Doyle Mar 11 '13 at 17:20
  • Any reason you're using `mysql_query` here? – tadman Mar 11 '13 at 17:23

2 Answers2

1

The function you're looking for here is called flush, this will allow you to flush the write buffers of your web server (Apache, Nginx, etc).

$pdo = new PDO('mysql:dbname=yourdb;host=127.0.0.1', 'root', '');
$sth = $pdo->prepare('SELECT * FROM `basket` WHERE `account_id`=?');
$sth->bindParam(1, $_SESSION['id'], PDO::PARAM_INT);
$sth->execute();

while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
    echo $row['number'];
    flush();
}

You're also using deprecated functions (mysql_*) you should consider replacing these with PDO or MySQLi (I've done this for you in my post).

Note: some browsers require a certain amount of data before they will display the content.

Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38
  • Thank you very much for your post, although PDO isn't my way of using it, i'm sticking to mySQLi ;), I only posted in mySQL for simple viewing – Curtis Crewe Mar 11 '13 at 17:40
1

How about taking a different approach...

while($row = mysql_fetch_assoc($res)) {
    $search[] = $row['number'];

}

echo json_encode($search);

In your success callback function you just iterate through your json_encoded array of basket elements using jQuery each()

loop through json array jquery

http://api.jquery.com/jQuery.each/

Community
  • 1
  • 1