tags:

views:

53

answers:

2

Hi,

Is there anyway with jQuery to pop up a message to the user that the database record that they are in, has been changed and that they need to refresh in order to pick up changes?

So basically, if they are viewing a record, walk away and then come back, where the user is presented with a message that the record you are currently viewing has changed - pls refresh.

Thanks.

+3  A: 

Sure, this very site does it.

How it roughly works:

  1. Using setInterval and $.ajax(), the client polls a backend script ever X seconds.
  2. The backend script checks the database and returns some sort of data - JSON is likely preferable in this case - indicating whether or not
  3. On the client side, the JavaScript parses the response from the server and acts accordingly.

Some caveats:

  • If there is any sort of traffic, this has the capability to bring a server to its knees. Take great care when determining the frequency of the polling.
  • I suggest limiting the total number of times per page load that the script is able to poll the server (e.g. after 20 times, the script stops polling). This way, you won't waste cycles when users leave the page loaded in their browser and walk away, for example.

Alternatively, you could look at Comet, which is more technically difficult and requires a great deal of server setup/sysadmin type knowledge to get working properly.

cpharmston
A: 

Yes, this is possible but there are a lot of parts you'll need:

First, some server-side code to that can check whether or not a record has been updated. I can't really give you any info on this step without more information on the environment you are working in.

Second, you'll need to use jQuery's ajax features to send an ajax request from the page every so often. In the callback function for that ajax request, you can check whether or not the ajax response says the record was updated.

Third, you simply need to decide how you want to let the user know that the record has changed. You could simply insert some text somewhere on the page, or you could get fancy and create some sort of dialog to let them know. Or, if you wanted, you could even just refresh the page for them instead of telling them that it has been updated.

Something like this:

function checkForUpdates() {
    $.getJSON('/theUrlForUpdateChecker', { record_id: 23 }, function(json) {
        if (json.isRecordUpdated) {
            var message = 'The record has been updated, please refresh the page';
            $('#notificationArea').text(message);
        }
    });
}

//execute it every 60 seconds (60000 milliseconds):
setInterval(checkForUpdates, 60000);

I used setInterval for simplicity, but for the interest of saving resources you probably would want to use setTimeout over and over, and stop checking for updates once you know a record was updated.

TM