A common use of AJAX is to get some data from a database and then display it on a web-page.
Also a common issue with AJAX calls is that it intercepts the request for data and tries to handle it locally. If it can’t only then is the request forwarded to the server. This is done to improve the performance of the web-page.
But this can have a serious side effect where after the first call to the server for data, subsequent requests are handled locally even though the data on the server side may have changed.
This is, most often, caused by a standard request string being used again and again.
For example if you want to fetch data from table ‘employee’ to display a list of employees then your request string (for HTTP GET) might look something like:
After getting the initial list of employees if any changes are made in the database they will not be reflected on the webpage even if you click the refresh button on the browser. The only way you will be able to see the ‘fresh’ data is if you reopen the page in a new browser window.
This is because every time the data listing request is sent using AJAX the XMLHttpRequest is intercepted by the browser, the request string checked and if found the same the request is responded to at the client side itself using cached data. Thus the ‘fresh’ data is never obtained from the server because it never gets the request for ‘data’.
How to solve this?
It is very simple to solve this problem. Just add a parameter with changing values to the string. For example:
Here the ‘rndmparameter’ parameter will have a random number assigned to it every time the request is made. This will make the request string different every time. Thus the request will be forwarded to the server and not be handled locally.
The parameter can have any name and any changing value. It need not even be random value. You could toggle a boolean variable ‘true’ and ‘false’ between subsequent requests.