Reputation: 14406
Using ajax and jQuery I would like to auto-update some divs every 5 minutes using values from a database.
For example:
<div id="1">One</div>
<div id="2">Two</div>
<div id="3">Three</div>
<div id="4">Four</div>
id="1"
is the id value of the corresponding database primary key. I would like to check that key against the database and if One
has changed, the div will show the new text instead.
What would be the best way to mass update these values asynchronously?
Upvotes: 0
Views: 529
Reputation: 22395
Following on from Marc B's idea, for the jQuery processing you could do something along the following:
var postString = 'check_ids=1,2,3,4';
$.get('/check-for-update', postString, function(response) {
$(response).each(function() {
$('div#' + this.id).html(this.txt);
});
}, 'json');
As a side note it's not recommended to use just numbers as IDs. Consider prefixing them with something meaningful like entry_1
entry_2
etc
Upvotes: 2
Reputation: 360572
Have your client-side script build up a list of IDs to be checked, send them to the server. The server can do its query using a WHERE id IN (1,2,3,4) AND date_changed > $last_checked
type query. Build up an array keyed with those IDs:
$array[] = array('id' => 1, 'txt' => "new text for div #1");
$array[] = array('id' => 4, 'txt' => "new text for div #4");
echo json_encode($array);
When the client gets the response from the server, simply iterate over that array and update the corresponding divs.
This way, you're doing only a single AJAX call, running only a single query, and one script invocation handles updating all the changed divs. This is especially useful if you're using PHP's default file-based sessions. If you fire off 4 ajax calls in short order, they'll have to be processed serially, as PHP locks the session file while a script is using it. Response time would tank as each ajax request could only be processed in sequence rather than in parallel. Less HTTP overhead as well, since you're doing only a single request rather than 4 separate ones.
Upvotes: 4