14

Javascript:

function atualiza() {
  document.getElementById('badge').innerHTML = location.reload();
}

I know the "location.reload()" will refresh the page...

HTML:

<img id="badge" src="<?php echo $cms_url; ?>/imaging/badge.php?badge=$mygroup['badge']; ?>" />

I need to freshed the src="" or <img /> without refreshing the page.

jcsantos
  • 195
  • 1
  • 1
  • 9

5 Answers5

21

See this: Updating a picture without page reload

document.getElementById('yourimage').src = "url/of/image.jpg?random="+new Date().getTime();

anyways, this was copied off that thread and apparently it should reload the image.

Community
  • 1
  • 1
Kevin
  • 708
  • 2
  • 9
  • 20
15

Change your img tag to this:

<img id="badge" src="$cms_url/imaging/badge.php?badge=$mygroup['badge']; ?>">/imaging/badge.php?badge=<?php echo $mygroup['badge']; ?>" />

Then you can use below code to change your image source on click of a button, anchor or whatever:

document.getElementById("badge").src="new image src here";

You can use jQuery as well:

$("#badge").attr("src", "new image src here");
Felix
  • 37,892
  • 8
  • 43
  • 55
9

Maybe the javascript i wrote is usefull for someone who reads this question. it ads a timestamp to every image to break the browser cache:

<script type="text/javascript">  

    function replaceSrc()
    {

        var images = document.getElementsByTagName('img');

        for(var i = 0; i < images.length; i++)
        {
            var dt = new Date();
            var img = images[i];

            if(img.src.length >= 0 & img.id != 'idImageNoTimestamp')
            {
                img.src = img.src + "?" + dt.getTime();
                //javascript:alert(document.lastModified);
            }
        }
    }
    replaceSrc();
      </script>

you can exclude some images by using the id attribute. I used it to exclude Google static maps images. if you don't need it, remove:

 & img.id != 'idImageNoTimestamp'
Aurora
  • 725
  • 1
  • 8
  • 17
  • 2
    I like this, but if you want this in a page that reloads only parts it needs to be `img.src = img.src.split("?")[0] + "?" + dt.getTime();` – Dolphin Oct 02 '17 at 12:24
1

For AngularJs, we can add directly in html file like this:

Html:

<div ng-controller="MyCtrl1"><div ng-repeat="img in images"> <img ng-src="{{img.image}}?_={{generatingNewDate}}"></div></div>

Ctrl: $scope.generatingNewDate = new Date().getTime();

You can have a look at this : https://jsfiddle.net/k614L8tt/

divy3993
  • 5,732
  • 2
  • 28
  • 41
yaqub
  • 63
  • 2
  • 9
0

Why do you need to do this?

<img id="badge" src="<img id="badge" src="$cms_url/imaging/badge.php?badge=$mygroup['badge']; ?>">/imaging/badge.php?badge=<?php echo $mygroup['badge']; ?>">

when you may do this

<img id="badge" src="<?php echo $cms_url. '/imaging/badge.php?badge='.$mygroup['badge']; ?>">