I have an ajax application where the client might lookup bunch of data frequently(say by key stroke), the data gets updated on the server side once or twice a day at fixed times by a demon process. To avoid visiting the server frequently, I store the data in a xml file, so the client downloads it once when the page first loads, then look the data up from local data file via javascript. But the user might load the page shortly before the changes, then start using it without ever refreshing the page, so the data file never gets updated, hence keep telling user the new data is not available. How do I solve this issue?
If the data load is not very large... Include the data in the main document as an XML island. Either form it in document generation (aspx, php, whatever) or fill in (via ajax calls) a reserved document node upon loading. This way, your user always has the latest data, you do not have to worry about caching, and life is much simpler.
If it is large, fill in that node as needed via ajax calls.
One obvious option is to add some AJAX that polls the server every x
minutes. If the data needs refreshing just show a non-blocking message somewhere obvious on the page notifying the user that fresh data is available and provide a link to refresh the page. As an extra you might want to provide a button for the user to click if they want to check for fresh data (rather than waiting for x
minutes to elapse) themselves.
If you use a HEAD request you can just check the last-modified header.
You said that the update time is FIXED? So when the user visit your page SHORTLY before the update time to come, you can set a javascript variable to you page that indicate how many minutes, for example, until the next update, and run a client-side timer such as:
timer = { run: function() { if( now + minuteToUpdate > updateTime - startVisitTime ) {
// make ajax request here to update XML file
}
},
interval: //you can determine this since this will run in client-side
}
Do not you POLLING in this stiuation because it's waste and stressed to call server every time.
You can set some SESSION variable to help this run better and more exactly
Justin
You should set the appropriate HTTP cache headers for that generated XML file so any client request past that time will get the new version and cache it locally, like any other static content.
What runtime said...
Or, since update times are fixed and infrequent, then when you serve your XML, also include a cache expiration time as an element or custom header. This way, if your user visits the site 1 minute before the XML update, you can code your client to expire its cache and update itself on the next request made after that 1 minute mark.