We help IT Professionals succeed at work.
Get Started

How to get an ajax call to change an img src and update the displayed image without manual browser refresh

James Froggatt
on
78 Views
Last Modified: 2020-02-23
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);

Open in new window


This sends latitude and longitude coordinates from an autosuggest drop down box to my php code at latLongToMap.php.

latLongToMap.php does a load of processing and creates an image file that is returned to the ajax request by

echo ($img);

Open in new window


This code then changes the img src of

  <img id="myLocationImage" src="worldmap-withdot.jpg" width="150" height="150">

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.

My ajax problem in real time
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...
Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 6 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE