Networking, Programming and Graphics - Tutorials
ONLINEHOWTO.net Tutorials Category

Prevent AJAX scripts from caching

Type: Code Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Level: Intermediate Networking, Programming and Graphics - Tutorials Networking, Programming and Graphics - Tutorials 
Networking, Programming and Graphics - Tutorials
Date: 2008-Jul-06
Networking, Programming and Graphics - Tutorials
Visited: 7821 times
Networking, Programming and Graphics - Tutorials
Rating: Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Published: Ivory Morhuld

AJAX is modern new technology which gives you an advanced way to improve the quality, speed and interactivity of internet applications. But the applications which intensively using AJAX, have one problem. To request data they make a URL post to server side script. This URL is cached by the client browser and even the server will serve new data, old data will be received by the browser.
var url='ajax.php?data='+str;
To solve this problem we will use some small fix. We have to add something unique to the URL, which will be with different value each time when the request will be sended. To do this we will use some value from current time.

To get the current time we will create an variable named date and will assign Date() object to this variable. Next using getTime() property on date variable will get the current time in new variable named timestamp.
var date = new Date();
var timestamp = date.getTime();
And now we can add this new value of time to the AJAX URL to get unique URL each time when AJAX script make request to the server side script.
var url='ajax.php?data='+str;
var date = new Date();
var timestamp = date.getTime();
url=url+'&time='+timestamp;
Please note that you have to get current time each time when you prepare to make each AJAX request. If you get time from current date in the beginning of script and later you want to use the value from this variable you will get identically values for time and your AJAX URLs.

For more explanation how AJAX work and how to use it you can visit our AJAX section of tutorials and to meet with AJAX features and possibilities.
Rate this tutorial:                    
Post Comment


    • posted on 2009-May-28 | 06:34:20 AM
      two week i searching for resolution about this problem and i found it and now this woks!!!
    • ( s_hussain_y [ at ] yahoo . com ),

      posted on 2009-Dec-09 | 10:51:49 PM
      while i was developing an application for a client, during testing and debugging i used to clear catch and open fresh browser for the ajax to work, your tutorial solved my poblem and now i do not need to do extra time consuming.
      thanks for the nice tut.
      keep up the good work :-)

    • posted on 2010-Feb-01 | 12:44:30 AM
      Thanks for the good words :-)
Need a specific tutorial? Do not hesitate and submit a request!
Your e-mail: