3

I'm trying to get my ajax to request information from the server and also keep it alive for at least 1 minuite before having a break and restarting and getting and passing a new streamitem_id if their were one inserted since the last call.

Currently it runs so fast and only once and I don't understand why.

AJAX

<script type="text/javascript" charset="utf-8">

function wait() {
    var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
    $.ajax({
        type: "POST",
        url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
        async: true,
        cache: false,, 
        dataType: "json",
        data: {streamitem_id: streamitem_id}, 
        success: function (response) {
        setTimeout("wait()",1000);
            $("#homestatusid").prepend("MY INSERTED RESPONSE");
        },
    });
}
$(document).ready(function(){
wait();
}); 
</script>

PHP

if (isset($_POST['streamitem_id'])) {
$lastID = (int)$_POST['streamitem_id'];

if(empty($lastID)) {
 die('timeout');
}
else {
$following_string = $_SESSION['id'];
$result="SELECT d.*, c.*, u.*
  FROM streamdata          AS d
  JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
  JOIN users               AS u ON u.id = c.comment_poster
 WHERE d.streamitem_id > '$lastID'
   AND c.comment_poster = '$following_string'
   AND (d.streamitem_creator  = '$following_string')
   OR d.streamitem_creator IN $friendlist
   AND d.streamitem_type_id NOT IN ('3')
   ORDER BY '$lastID' DESC LIMIT 1";
$result = mysqli_query($mysqli, $result) or die(mysqli_error($mysqli));

while ($resultArr = mysqli_fetch_array($result)) {
$json = array();
    $json['streamitem_id'] = $resultArr['streamitem_id'];
    $json['streamitem_content'] = $resultArr['streamitem_content'];
    $json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
    $json['comment_id'] = $resultArr['comment_id'];
    $json['comment_content'] = $resultArr['comment_content'];
    $json['comment_poster'] = $resultArr['comment_poster'];
    $json['comment_datetime'] = Agotime($resultArr['comment_datetime']);
    $json['comment_streamitem'] = $resultArr['comment_streamitem'];
    $json['username'] = $resultArr['username'];
    $json['id'] = $resultArr['id'];
    $json['first'] = $resultArr['first'];
    $json['middle'] = $resultArr['middle'];
    $json['last'] = $resultArr['last'];
echo json_encode($json);
}}}
Dan Barzilay
  • 4,974
  • 5
  • 27
  • 39
dave
  • 1,009
  • 5
  • 15
  • 26
  • Why do you send the id via both GET and POST? And get rid of the second comma in `cache: false,,`. And don't pass as string but a function to `setTimeout()`: `setTimeout(wait, 1000)` – ThiefMaster Sep 16 '12 at 12:25
  • Silly mistakes rectified with the same issue. I don't know if its my ajax or my PHP JSON. – dave Sep 16 '12 at 12:33

2 Answers2

0

setTimeout does not work like you expect. An ajax-request can't be "kept alive" like you want. The request is sent, the PHP-script returns the content and the ajax-script get's the result. All this happens within ~1-2 seconds.

If this is used for some sort of stream (as it looks like), you would have to make the function repeat itself again and again over a small interval.

I've changed your code like this:

<script type="text/javascript" charset="utf-8">

function wait() {
    var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
    $.ajax({
        type: "POST",
        url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
        async: true,
        cache: false,
        dataType: "json",
        data: {streamitem_id: streamitem_id}, 
        success: function (response) {
            $("#homestatusid").prepend("MY INSERTED RESPONSE");
        },
    });
}
$(document).ready(function(){
setInterval(wait,10000);
}); 
</script>

The ajax-script will fire every 10 seconds. You can edit the speed yourself, but keep in mind that too many requests in a short timeperiod can make your server crash/go slow.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
  • This isn't true, the ajax call will last as long as it takes for the PHP script to close the connection, you can easily artificially keep the connection open as long as you want using PHP – Korvin Szanto Sep 16 '12 at 12:31
  • Well, yeah. You can do that, but that means that no content it returned to the js-script and that way, the update frequency on the stream will suck. – OptimusCrime Sep 16 '12 at 12:33
  • 1
    Huh? Look at my response, it will respond with content to the JavaScript with a latency of up to 50ms, (not counting cost and network time). That will suck versus checking every 10 seconds? – Korvin Szanto Sep 16 '12 at 12:36
  • It is working how I need it to now.. Tho no data is returned. IS my JSON in PHP wrong? – dave Sep 16 '12 at 12:41
0

In your PHP script, you'll need to use the sleep function in order to keep your connection alive.

Something like:

function callScript(callback) {
    $.post('myscript.php',{data:data},function(data) {
        if (data == -1) {
            return callScript(callback);
        }
        return callback(data);
    }
}

myscript.php

$interval = 50;
$iters = floor(1000 / $interval);
while($conditional === false) {
    if (--$iters < 1) { die(-1); } 
    sleep($interval);
}
echo $json;

While this isn't exactly what you need, it can easily be adapted to what you need. I've done this with other stuff, while costly, you can use a sql statements to wait for entries to be added etc.

Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49
  • Is their ANY possibility you could intergreate the above into my code for me please. I've been trying to get this to work for over a week now. Its really bugging me. – dave Sep 16 '12 at 12:42