Reputation: 1280
I'm using jQuery's $.get()
method to retrieve data from an external php file.
The code refreshes the data, however, because I'm refreshing two external files, the html for the second (messages.php) will refresh and then refresh again about 300ms after the first file (tasks.php) refreshes.
Aside from combining the tasks.php and messages.php into one (in this case I greatly prefer not), how would I do one call to refresh both?
In other words, how would you re-write this function?
Any advice is appreciated!
function refreshTopBar() {
var rootx = $('#admin_topbar_root').val();
var root = (rootx.match(/\//g) || []).length;
var userid = $('#admin_topbar_userid').val();
$.get(rootx + "qms/inc/tasks.php", {r:root, u:userid}, function(data) {
$('#mytasks').html(data);
setTimeout(refreshTopBar, 9000);
});
$.get(rootx + "qms/inc/messages.php", {u:userid}, function(data) {
$('#messages_li').html(data);
setTimeout(refreshTopBar, 9000);
});
}
refreshTopBar();
Upvotes: 0
Views: 878
Reputation: 10994
You can use $.when()
to pass the ajax requests and wait until both are done to execute a function.
function refreshTopBar() {
var rootx = $('#admin_topbar_root').val();
var root = (rootx.match(/\//g) || []).length;
var userid = $('#admin_topbar_userid').val();
var tasks = $.get(rootx + "qms/inc/tasks.php", { r: root,u: userid });
var msgs = $.get(rootx + "qms/inc/messages.php", { u: userid });
$.when(tasks, msgs).done(function (tasks_data, msgs_data) {
// return value is an array ['returned string', 'status', XHR Object]
// if one of them fails this won't run
$('#mytasks').html(tasks_data[0]);
$('#messages_li').html(msgs_data[0]);
setTimeout(refreshTopBar, 9000);
});
}
Upvotes: 2
Reputation: 358
You could use a sort of promise that calls the refresh function once both calls are completed. I've altered your code below:
function refreshTopBar() {
var rootx = $('#admin_topbar_root').val();
var root = (rootx.match(/\//g) || []).length;
var userid = $('#admin_topbar_userid').val();
$.get(rootx + "qms/inc/tasks.php", {r:root, u:userid}, function(data) {
$('#mytasks').html(data);
done();
});
$.get(rootx + "qms/inc/messages.php", {u:userid}, function(data) {
$('#messages_li').html(data);
done();
});
var done_int = 0;
function done() {
done_int++;
if (done_int > 1) {
setTimeout(refreshTopBar, 9000);
}
}
}
refreshTopBar();
This will wait until the done()
function has been called at least twice before it starts the timeout.
Upvotes: 1