Reputation: 646
I am writing a dynamic website that uses AJAX to check the status of inventory items between front-end and back-end employees of a firm. One employee submits a request and the people in the back see it pop up on a queue and then respond if the requested item is or isn't in stock. The front-end employee then sees the status of their request change appropriately.
The problem I am having, and perhaps there is a better way of doing things, occurs when the code uses AJAX to retrieve all active requests from a table in a database and then uses jQuery 's .empty() function to clear out the container div which holds all of the old requests(setInterval() every 2 seconds) and regenerates the queue using a PHP script which builds a on the fly based on the AJAX results.
The setInterval() function which calls the function that .empty() the container div causes queue to visibly disappear and reappear. Is there a better way of updating a queue using jQuery rather than emptying out the entire queue and then rebuilding it based on updated statuses? I cannot simply query for the latest request because the statuses of older requests may have changed and need to be updated as well.
Hopefully this is clear, if not then please ask what more information is need, and any help will be greatly appreciated, thanks!
Upvotes: 1
Views: 935
Reputation: 26766
Something like this...
$(document).ready(function(){Update();});
function Update() {
$.ajax({
url: 'http://example.com/url/to/poll',
success: function(data) {
$('#MyDiv').html(data);
setTimeout('Update()', 2000);
},
fail: function() {
//Something went wrong. Inform user/try again as appropriate
alert('Failed');
setTimeout('Update()', 2000);
}
})
}
It only starts the next 2s delay after the current one completes. Also, it never actually empties the Div, it just replaces the old contents with the new.
Upvotes: 2