How to get an ajax call to change an img src and update the displayed image without manual browser refresh
I have an Ajax call;
var xhr= new XMLHttpRequest(); // this executres when the ajax request in completed, i.e. the results // are sent back from php xhr.onload = function (){ document.getElementById("myLocationImage").src=this.responseText; } xhr.open("POST", "latLongToMap.php"); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("lat="+$latitude+"&lon="+$longitude);
My problem is that the ajax request does work, and does change the file on the server. But for me to see the image, I have to CONTROL-F5 my browser.
What do I need to do so I see the new image file without having to manually refresh my browser?
I have attached an animated gif (I hope it works) showing my problem. When the gray image appears, I have to CONTROL-F5 to see the new image.
Please help, I've played around with various ideas I've found on the internet, but with no joy.
Thankyou
James
PS: Note I'm aware it always says 'Toulouse' by the label, I haven't done that bit of my code yet...
AJAX
Last Comment
James Froggatt
8/22/2022 - Mon
James Froggatt
ASKER
.. I also notice, when I 'Inspect' the code in Google Chrome when the gray image is showing (before I have to refresh the page manually to 'see' the image) I see this code in the image src.
I'm not sure why I'm seeing a resource reference and not the actual file name.
Julian Hansen
Just change the src value of the image - it will automatically change
The src attribute of the image might take a relative path when you code it but on parsing the browser changes this to a full path - you can see this if you dump the contents of
<img src="abc.jpg">
You will get http://sourcedomain.com/images/abc.jpg (or similar)
When you set the src you need to include the path.
So you can either include the full path in the image value you return
OR
In JavaScript you can get the path of the existing src - strip off the filename and append the new one.
I'm not sure why I'm seeing a resource reference and not the actual file name.