0

How would I go about updating a div with a id every x seconds? I want it to update the users statuses which are contained inside this, that includes the time the amount of comments made on that individual post.

I've tried setInterval but it takes 10 seconds for the status to be added and then duplicates the status every x amounts of seconds after that. All I need is for the response data to be updated not the insertion of the comment to be re-added every 10 seconds.

HTML:

<div id='divider-"+response['streamitem_id']+'></div>

JavaScript:

$(document).ready(function(){
    $("form#myform").submit(function(event) {
        event.preventDefault();
        var content = $("#toid").val();
        var newmsg = $("#newmsg").val();

        $.ajax({
            type: "POST",
            url: "insert.php",
            cache: false,
            dataType: "json",
            data: { toid: content, newmsg: newmsg },
            success: function(response){ 
                $("#homestatusid").html("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'><a href='/profile.php?username="+response['username']+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+response['streamitem_id']+"');\">X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"</a><span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+newmsg+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</div></a><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'></div></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</div></a><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></div><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'><table width=100%><tr><td valign=top width=30px><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><td valign=top align=left><div class='stream_comment_inputarea'><input id='addcomment' type='text' name='content' style='width:100%;' class='input_comment' placeholder='Write a comment...'  onkeyup='growcommentinput(this);' autocomplete='off' onkeypress=\"if(event.keyCode==13){addcomment("+response['streamitem_id']+",this.value,'comment_list_"+response['streamitem_id']+"',"+response['id']+",'"+response['first']+" "+ response['middle']+" "+response['last']+"');this.value='';}\"><br/></div></div>");
            }
        });
        return false
    });
});

INSERT.PHP

$json = array();
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_id DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];


mysql_free_result($check1);

$check = "SELECT streamitem_timestamp FROM streamdata WHERE streamitem_creator='$user1_id' ORDER BY streamitem_timestamp DESC";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_timestamp'] = Agotime($resultArr['streamitem_timestamp']);
mysql_free_result($check1);



$check = "SELECT username, id, first, middle, last FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];

mysql_free_result($check1);

echo json_encode($json);
dave
  • 1,009
  • 5
  • 15
  • 26
  • 1
    Perform an AJAX call in jQuery, wrapped in a setInterval function. – jacktheripper Aug 05 '12 at 10:17
  • 1
    Hi Dave, can you show us what you have tried so far? We would need to see your full html (eg not PHP) and also to see your javascript that would pull the information from the server – Undefined Aug 05 '12 at 10:17
  • 1
    @jacktheripper setInterval, or even better, a function that calls itself on completion. – Undefined Aug 05 '12 at 10:17
  • @sam if you do that, wouldn't you get an infinite loop? Maybe it would still work, but it isn't pretty I think. Especially because every time your function is called, some data is stored in the memory, but because technically the first call of the function is still in play, it never gets deleted. – JarroVGIT Aug 05 '12 at 10:19
  • I've updated my complete question also noting my issues with setinterval. – dave Aug 05 '12 at 10:23

4 Answers4

1

You can use setInterval (see Documentation) or setTimeout (see Documentation).

Oussama Jilal
  • 7,669
  • 2
  • 30
  • 53
1

First wrap up the Ajax call in a single-execution function, with the callback function referring to the same:

$(function() {
    (function ajaxcall() {
       $.ajax({
        url: 'foo.php',
        data: {boo:'moo',goo:'loo'},
        timeout: function() { ajaxcall(); },
        success: function(data) {
            //do somethng with the data
            //done, now call the function again:
            ajaxcall();
            }
        });
    }());
});

Then in the PHP write something like:

$timeout = 30;
$pollinterval = .5;
$counter = 30;
while ($counter >= 0) {
//function which fetches fresh data and sets $test to true if data is returned
  list($test,$dataarray) = fetchdata();
  if ($test) { //JSON_encode the data array and send it
     echo JSON_ENCODE($dataarray);
     }
  else { //no fresh data, query the db again after wating for some time)
    usleep($pollinterval*1000);
    $counter -= $pollinterval;
  }
//timeout, return whetever you have!
echo JSON_ENCODE($dataarray);
SexyBeast
  • 7,913
  • 28
  • 108
  • 196
  • That looks promising. I've updated my question with my Insert.php page. How would I insert your php code into mine. – dave Aug 05 '12 at 15:00
  • I really couldn't understand your PHP code. Whatever be it, just follow the outline I gave, and it should work. – SexyBeast Aug 05 '12 at 15:14
  • Do I put my select function inside the while? And I suppose your $dataarray will be my $json and $test will be the function where I select from the database.. – dave Aug 05 '12 at 15:18
  • Obviously you put the `select` inside the `while` loop. In the `data` portion of the Ajax request, you can send a marker, say 57, which is the id of the last data item on the web-page currently. In the PHP script, inside the `while`, you query the DB for rows with that marker id > 57 (assuming it's an ascending primary key). If there are results, gather them and send them back immediately to the JS, else continue until timeout, after which you send an empty result set. – SexyBeast Aug 05 '12 at 15:52
0

Sounds like polling. You can include an AJAX call, that will send a request to a backend PHP script that will search the database for further update. if found, it will immediately return the new result. The client side JS on receiving the new data, will wait for say 30 seconds before making another request. If the PHP doesn't find any new data, then it will query the DB again, say after 5 seconds, and continue to do so until a script-defined timeout, say 25 seconds, occur. Then it will return an empty result, on receiving which the client side JS will immediately make another request.

SexyBeast
  • 7,913
  • 28
  • 108
  • 196
  • do I need to insert anything to do that? Or can I use something to just update after the page loads? – dave Aug 05 '12 at 10:58
  • You want to call the function from the moment the page loads, just include the ajax call within the `document.ready(function() {}`, else if you want to start it, say 5 minutes after the page loads, include it within a `setTimeout` function. Provide he same function name as the callback function to execute once the request completes, so that the function will continue to run on its own. – SexyBeast Aug 05 '12 at 11:41
  • Nothing I'm doing seems to be working. Could you provide me with an example maybe from the code I've posted in my original question please? – dave Aug 05 '12 at 12:21
0

I think this is what you're wanting, using Jquery:

HTML:

<div id="divider-whatever"></div>

Jquery:

$(document).ready(function() {

    setInterval(function() {
        div = $("#divider-whatever");
        $.get(data.php, function(responseData) {
            div.html(responseData);
        }, 1000);
        // change 1000 to whatever time you need
        // change data.php to the file where your data is coming from
    });

});

*not tested

Hope this helps!

Zack
  • 1,615
  • 18
  • 26