Search code examples
phpjqueryajaxlong-polling

No data from long polling in PHP


Basically, I'm trying to put together a live feed on my website for an external API that pushes all new data to my database,

Here's the current HTML code I'm using to grab my PHP file and get any new content added to the database

$min_id_result = $DB->select("SELECT `id` FROM `api_media` ORDER BY `id` DESC",true);
//Basically all this is doing is returning the latest ID in the database

var Id = "<?=$last_id_result['id'];?>";
function waitForPics() {
    $.ajax({
        type: "GET",
        url: "/ajax.php?id="+Id,

        async: true,
        cache: false,

        success: function(data){
            var json = eval('('+ data +')');
            var img = json['img'];
            if(json['img'] != "") {
                $('<li/>').html('<img src="'+img+'" />').appendTo('#container')
            }
            Id = json['id'];
            setTimeout(waitForPics,1000);
        },
     });
}

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

Here's the ajax.php file I'm using to process the database

$min_id_result = $DB->select("SELECT * FROM `api_media` ORDER BY `id` DESC",true);
$next_min_id = $min_id_result['id'];

$last_id = $_GET['id'];

while($next_min_id <= $last_id) {
    usleep(10000);
    clearstatcache();
}

$qry_result = $DB->select("SELECT * FROM `api_media` ORDER BY `id` DESC");

$response = array();
foreach($qry_result as $image) {
    $response['img'] = $image['image'];
    $response['id'] = $image['id'];
}
echo json_encode($response);

The problem I'm having is it's returning no data to me from the request, It appears all correct to me but obviously a second developers eye appears better at times


Solution

  • This should work:

    while($next_min_id <= $last_id) {
        usleep(10000);
        clearstatcache();
        $min_id_result = $DB->select("SELECT * FROM `api_media` ORDER BY `id` DESC",true);
        $next_min_id = $min_id_result['id'];
    }
    

    inside the while you wait for a specific parameter to change, but you need to give it the chance to change.

    The variables do not change themselves, you need to refresh them.