I normally develop with VBA and MySQL, but have been tasked with creating a live dashboard to be put on screens around my office. For this I’m using PHP and javascript. The dashboard contains two main sections, one calls website traffic data through the google analytics API, the other calls sales data from our internal DB.
I have the seperate halves written in PHP in seperate modules that I’m calling with the code below from the dashboard webpage, using a loop to refresh each module independently every ten seconds. The problem is that I’d like to include two timers on the screen counting upwards in seconds from the last time each of the modules was loaded, I’m using the following code to try and reset a variable with the current time to facilitate this when each document is loaded.
var sales_string_unix = 0;
var sales_string_google = 0;
setInterval(function(){
$(document).ready(function() {
$('#google_data').load('fetch_google_data.php');
sales_string_unix = new Date().getTime();
});
}, 10000);
setInterval(function(){
$(document).ready(function() {
$('#sales_data').load('fetch_sales_data.php');
sales_string_google = new Date().getTime();
});
}, 10000);
My problem is that the timestamp variables reset every ten seconds when the loops execute, rather than when the modules are refreshed. So far 6hrs of Google has returned nothing useful and I expect I’m probably missing something simple thats just outside of my experience. Any help would be appreciated, thanks in advance.
You need to put the timestamp update code in the callback function of the
load()which runs when the AJAX call has completed. You also don’t need thedocument.readyhandler inside each function. Try this:Be aware however, that those variables will only be filled once the AJAX call has completed, so you cannot use them directly after the AJAX calls themselves. You would need to run or call the code which relies on the timestamps from within the callback function itself.