0

I've been searching and searching with no solution. I have this html:

<div class="content_wrap"> 
  <script src="jslib/random_image.js"></script>
</div>

And a link:

<li><a href="javascript:location.reload();" target="_self">Random image</a></li>

But instead of reloading the whole page (lame) I want to either refresh the div (not sure whether it's possible) or at least refresh random_image.js.

How can you do this with jQuery? Or PHP, or something else?

Charles
  • 50,943
  • 13
  • 104
  • 142
Brian Johnson
  • 131
  • 2
  • 11

3 Answers3

0

Assuming you have img in div

<div class="content_wrap"> 
  <script src="jslib/random_image.js"></script>
  <img id="random_image" href="">
</div>


function updateNewImage(){
//make ajax to server 
// get new url store it in variable new_href
// update random_image  $("$random_image").attr("href",new_href);
}
<li><a href="javascript:updateNewImage();" target="_self">Random image</a></li>

you can call a function on onclick which will get the new image url using ajax and then you can update img href location.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Vivek Goel
  • 22,942
  • 29
  • 114
  • 186
0

Haven't tested the code, but assuming no major mistakes, this should do it. I'm assuming you have jQuery (can also be done with simple js but might as well use jq):

<div class="content_wrap" id="content_wrap"> 
  <img id="rndImg1" src="clicktorelodme.png"/>
</div>

<script>
function reloadImage(imgId) {
    String randomImgSrc = "anewimgsrc.png";
    $("#content_wrap").find("#"+imgId).attr("src", randomImgSrc);
}
</script>


<li><a href="#" onclick="reloadImage('rndImg1'); return false;">Random image</a></li>

Looking at your response to another answer I understand you want to do more than refresh the image, you want to load code which does "stuff" like set the image, set the title etc.

To do that you need to do something else, like add a new script element to the page, and it can do whatever you want. Look at this answer to learn how to do that.

Community
  • 1
  • 1
TheZuck
  • 3,513
  • 2
  • 29
  • 36
0

You first of all need a way to refer to your DIV, for example an id:

<div class="content_wrap" id="randomImage">
    <script src="jslib/random_image.js"></script>
</div>

Then to reload the DIV you can simply rewrite its content. This might be cached by the browser, so, depending on how the script work, you might be forced to add a dummy parameter to the call.

You can re-declare the whole DIV emptying it and recreating with append(), or you can use .load() which offers more control:

$('#randomImage').load('jslib/random_image.js?dummy='+Math.random(),
    function(res, status, xhr){
        if ('success' != status)
        {
            // Do something with the image, maybe load a default one
            return;
        }
});
LSerni
  • 55,617
  • 10
  • 65
  • 107