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?
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_checkedtype query. Build up an array keyed with those IDs: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.