I’m having issues with a javascript global variable (called TimeStamp) not being defined onload…at least I think that’s the problem.
I start with this, defining TimeStamp.
$(document).ready(function(){
// AddTest();
var TimeStamp = null;
waitForMsg();
});
…waitForMsg then runs using TimeStamp and updated it on successful completion of the ajax call. At least that’s the idea, but at the moment nothing runs because “TimeStamp is not defined”…even though I defined it earlier! (urgh).
If I re-define Timestamp within waitForMsg it just gets reset instead of using the updated value from the successfull ajax function.
function waitForMsg(){
$.ajax({
type: "POST",
url: "backend.php",
async: true,
cache: false,
timeout:50000, /* Timeout in ms */
data: "TimeStamp=" + TimeStamp,
success: function(data){
var json = eval('(' + data + ')');
$('#TextHistory :last-child').after('<p>' + json['msg'] + '</p>');
TimeStamp = json['timestamp'];
setTimeout(
'waitForMsg()', /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$('#TextHistory :last-child').after('<p>' + errorThrown + '</p>');
setTimeout(
'waitForMsg()', /* Try again after.. */
"15000"); /* milliseconds (15seconds) */
},
});
};
As always any help is greatly appreciated.
Dan.
change
to
That way the it will live in the global scope and not just in the scope of the ready function.
As a further note, you should change your
setTimeoutstatements from the formsetTimeout(string to eval,delay)tosetTimeout(function reference to run, delay). like so:so you avoid the unnecessary
evalcall.Further more, consider changing
to
so that you get the benefit of native JSON parsing in modern browsers.
Even better, let jQuery deserialize the JSON for you by adding
dataType: 'json'as parameter on the ajax call 🙂