Disable Caching for XMLHttpRequest (Javascript)

How to use setRequestHeader to disable browser caching for XMLHttpRequest

XMLHttpRequest (Javascript)

XMLHttpRequest is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment. XMLHttpRequest can be used with protocols other than HTTP, and the returned data can be in the form of XML, JSON, HTML, or plain text.

 

Browser Caching

Browser cache is a buffer memory of the web browser in which previously accessed resources such as images or fonts are kept as a copy on the user's local computer. If a resource is later needed again, it can be retrieved from the cache faster than if it had to be downloaded again from the web. While this is very good for static resources, it causes problems for dynamic content. Browser caching is often a problem in connection with XMLHttpRequest, since the content here is usually dynamic and varies depending on the data transmitted.

Disable Browser Caching for XMLHttpRequest

Browser caching can be controlled by both the request header and the response header.
The following example shows how to disable browser caching using the request header.

 

The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header.
If you use "setRequestHeader", you must call it after calling "open" but before calling "send".

 

Javascript Sample Code:

// add form data
var fd=new FormData();
fd.append('Name',name);
...

// XMLHttpRequest
xhr=new XMLHttpRequest();
xhr.open('POST','https://www.example.tld/example.php');


// disable browser caching in request header
xhr.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');
xhr.setRequestHeader('Expires', 'Thu, 1 Jan 1970 00:00:00 GMT');
xhr.setRequestHeader('Pragma', 'no-cache');

// send data
xhr.onreadystatechange=function(){if(xhr.readyState===4){if(xhr.status===200){ /* do something */ }else{ /* error */ }}};
xhr.send(fd);

 

If the target of the XMLHttpRequest is a PHP file, you should also note the following article, which describes how to control browser caching in the response header of a PHP script. So you can control both the request header and the response header.

Disclaimer: The information on this page is provided "as is" without warranty of any kind. Further, Arclab Software OHG does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement