Obay
Obay

Reputation: 3205

Dynamically created image doesn't show when <img>'s src is refreshed to point to it

I have a javascript function

generateGraph() {
    ...
    jQuery.get('chart.php?month='+month+'&year='+year);
    document.getElementById('graph').src = 'charts/'+month+'_'+year+'.png';
    ...
}

which is called onChange. It basically creates, if not exists, or refreshes if already exists, a PNG image (using the first line above) and supposedly displays the generated image (using the second line above).

The first line works, but the second one doesn't. Meaning, the image is generated, but the second line can't display the image, unless the page is reloaded, or if the image being referred to already existed before the page was loaded (meaning the 1st line just "refreshed" the image)

Any ideas as to why this is and how to fix it?

Thanks much for your help in advance!

Upvotes: 3

Views: 528

Answers (4)

Xavi
Xavi

Reputation: 20439

Try this:

generateGraph() {
    ...
    jQuery.get('chart.php?month='+month+'&year='+year, function() {
        document.getElementById('graph').src = 'charts/'+month+'_'+year+'.png';
        // as mentioned by others this also works and is in the jquery style:
        // $("#graph").attr("src", "charts/" + month + "_" + year + ".png");
    });
    ...
}

If I understand everything correctly, a call to chart.php generates an image at charts/month_year.png. If this is correct, your original code sent a request for the image immediately after sending a request to generate that image. This doesn't give enough time to the server to create and post the image to charts/month_year.png, which is why nothing appeared.

Upvotes: 2

Justin Ethier
Justin Ethier

Reputation: 134167

You can solve this problem by creating an image that is never displayed. That will download the image file. Then, when this image is loaded, swap out the one on your page with the downloaded image:

var newImage = new Image();
newImage.onload = function(){
    // Update existing image src on your page
    }
}
newImage.src = "URL to your image";

Upvotes: 1

karim79
karim79

Reputation: 342635

Update the src within $.get's success callback, to ensure that it happens upon completion of the request:

generateGraph() {
    ...
    jQuery.get('chart.php?month='+month+'&year='+year, function() {
        jQuery('#graph').attr("src",'charts/'+month+'_'+year+'.png');
    });

    ...
}

Upvotes: 2

alemjerus
alemjerus

Reputation: 8268

It looks like your image generation process takes nonzero time, and assigning src right after jQuery call just does not fit in time to get the image to be ready, and after you reload the page, the image is ready for sure. So add some AJAX verification for the image creation readiness.

Upvotes: 1

Related Questions