Based on the comments of the author of the question, here is one of the possibilities to achieve the desired goal simply and effectively.
Create a PHP file named get-image.php
and put the following code inside it
<?php
if (isset($_GET['ajax'])) {
$numRand = rand();
echo "<img src='imagem.png?{$numRand}'>";
}
Now, create a PHP or HTML file with the name you prefer and put the following code
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Burlando cache do navegador com AJAX</title>
</head>
<body>
<div id="imagem"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script><script>functionattImagem(){$.ajax({url:'get-image.php',type:'GET',data:'ajax=null',success:function(data){$("#imagem").html(data);
}
});
}
setInterval("attImagem()", 1000);
</script>
</html>
Explaining logic
When you enter your main file (which contains the HTML and JavaScript code), jQuery is included, and a function that will be fired every second. This function will call via AJAX (without updating the page) the file get-image.php
The get-image.php file has the function of generating a random number and assigning the image name as a GET parameter, making the browser understand that the image is another one, not the one that was previously loaded.
Final considerations
- If you want to change the name of the image that will be requested, look for
linha 5
of the get-image.php
file, and change the image.png to the name of your image, as well as the path (if it is in another directory).
- In the script above, the image will be displayed in the div called
imagem
, if you want, you can change the name, but do so both in the ID of the div and inside the AJAX function, where%
- To increase or decrease the interval between updates, change the value
$("#imagem").html(data);
.
- When dealing with an image, setting a very low value may cause the image to not be displayed and may also overwhelm the server where the image is hosted.