views:

84

answers:

4

Hello,

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!

+1  A: 

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.

alemjerus
thanks for the explanation. helped me understand what was happening
Obay
+1  A: 

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.

Xavi
it works! thanks man!
Obay
+2  A: 

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');
    });

    ...
}
karim79
+1 for refactoring away raw JavaScript.
Skilldrick
+1  A: 

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";
Justin Ethier