tags:

views:

20

answers:

2

I want to load picture from web server without refreshing the page. I have simple page:

<body><h1>Test</h1>
      <div id="mydiv">
         <img src="animals.jpg"/>
      </div>
</body>
</html>

the point is that animals.jpg content changes (i.e now animals.jpg can be picture of wolf but after minute it will be changed to a cat) however the name(animal.jpg) stays ( server overwrites the image content only ) so what i want is when i click on the picture it will re-load it from the server.

what i did so far (actually it's made of pieces of examples i found :) ):

    $(document).ready(function(){
        $('#mydiv').click(function(){
        //$('#mydiv').load("animals.jpg") // loads text instead of image
        //$("#mydiv").append("<img src='animals.jpg'/>"); // appends old picture
        //$("#mydiv").html("<img src='animals.jpg'/>") // not responds at all
    }); 
})

not working, see the comments.

Though I can load html's:
loadme.html:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/&gt;&lt;/script&gt;
<script type="text/javascript">
   $(document).ready(function(){
     $('#mydiv').click(function(){
     $('#mydiv').load("h1.html")
   }); 
 })


</script>

</head>

<body><h1>Test</h1>
<div id="mydiv">
load me!
</div>
</body>
</html>

h1.html:

Text


now when i change h1.html 'text' on something else and i click on 'load me!' in load.html it will updated content always. That's what i want to achieve with images :/

A: 

Easiest way, for me:

<img id="myimg" src="animal.jpg"/>

Just set the src attribute with Javascript:

function f()
{
   var img = document.getElementById("myimg");
   img.src = "your_new_pic.jpg";
}

Of course, if you need animations or other cool stuff, it's better to use JQUERY.

Pablo Santa Cruz
Don't think you understood the question. He's looking for a way to get JavaScript to **reload** an image (cachebusting).
ceejayoz
+1  A: 

You need to change the image's src attribute to get it to reload. As the src is supposed to stay the same, append a random string to the end of it. This'll make the browser think it's a new image.

$('#mydif>img').attr('src', 'animals.jpg?random=' + Math.random());
ceejayoz
Thanks, it's finally working!. $('img').attr('src', 'animals.jpg?random=' + Math.random());( with a little modification )
Qwerto