Cloud
Cloud

Reputation: 1034

Why cache is not clear in ajax request?

I have external js file that run home.php file by using ajax request.

Everything is fine in my code. But the cache is not clear even I add random function in url.

Here is my js code.

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }    
}
xmlhttp.open("GET","http://myurl/home.php?t="+Math.random(),true);
xmlhttp.setRequestHeader( "Pragma", "no-cache" );
xmlhttp.setRequestHeader( "Cache-Control", "no-cache" );
xmlhttp.send(); 

Every time I call this js file from index.php, I get cache result.

To avoid cache problem, I already add unique id in url. But it doesn't work. So, please give me any suggestion to solve this problem.

Upvotes: 1

Views: 213

Answers (1)

Armen
Armen

Reputation: 4202

To avoid js or css files include caching issue ( answer to your question in question comments ), you have to change their include links automatically after each change, for this you can use filemtime("file")in recourse include step in html

filemtime return you file creation time, look for manual here about - http://php.net/manual/en/function.filemtime.php

<script 
   src="http://url/some.js?t=<?php filemtime("PATH_TO_FILE/some.js") ?>" >
</script>

<link rel="stylesheet" type="text/css"
   href="http://url/some.css?t=<?php filemtime("PATH_TO_FILE/some.css") ?>" >

So by this way during each modification of some.js or some.css their creation time will change and to your home.php will be added new url links (http://url/some.js?t=14....) to that recourse and bowser will have to load them again

Upvotes: 1

Related Questions