Reputation: 67
I have index.php page which makes a ajax call to thread.php by sending the variable "dateposted". The thread.php returns a json which is being looped through in my index.php and the last value is sent back into the ajax call again. All this works fine. However, the problem i face is when i put thread.php in autorefresh using
<meta http-equiv="refresh" content="2">
When i do this, the returned response in my ajax call includes this and the json results which throws my looping of the json array off. I can remove the above code since i need thread.php to be constantly refreshing to poll data from the server. How do i get around this issue:
For reference: thread.php
<meta http-equiv="refresh" content="2">
if(!isset($_GET['dateposted']))
{ $lastpost = 0;
}
else
{$lastpost= $_GET['dateposted'];}
$latestmsgs = retrieveNewMsgs($lastpost,$currtime);
?>
<?php echo json_encode($latestmsgs);?>
index.php
var returnValue = (function() {
var dateposted = null;
return function() {
$.get("thread.php", { "lastMessage": dateposted }, function(result) {
if(result) {
for (var i = 0, len = result.length; i < len; i++) {
var msgs = result[i];
var newDiv = $("<div><img src='" + msgs[0] +"'/>" + msgs[2] + msgs[3] + msgs[4] + msgs[5] + "</div><br>");
$('#chatContents').append(newDiv);
}
}
dateposted = result[result.length-1][5];
}, "json");
}
})();
Upvotes: 1
Views: 419
Reputation: 1039268
You could use the window.setInterval function to execute some javascript code at regular intervals of time that you define. So remove the meta refresh tag and place your AJAX call inside setInterval
:
// poll the server every 10 seconds for new data
window.setInterval(function() {
$.get("thread.php", ...
}, 10000);
Upvotes: 1