views:

59

answers:

2

Hi, I am having some trouble figuring out why I cant load an image with jQuery. It seems to me a browser cache problem, but I am not sure. I am doing an ajax call that returns me the path of some generated image. On the complete method I want to replace the existing image that I have for this new one. What happens is that the src of the image changes but my image stays the same. Here's part of the code. Could you tell me if I'm doing something wrong?

'onComplete' : function(response)
{
 var img = new Image();

 $(img).load(function()
 {
  $('#imagecontainer').children("#imagepreview").remove();
  $('#imagecontainer').append(this);
  $(this).fadeIn();
 }).attr('src', response);
}

If I type attr('src', 'image.jpg') it works, also if I alert response it gives me 'image.jpg' but if I put attr('src', response) it doesnt work!

Thanks

A: 

Without knowing which jQuery method you are using to issue the request, I can't be sure of the problem; but as a guess I would say try response.responseText instead of response.

Also, the line:

$('#imagecontainer').children("#imagepreview").remove();

May as well be:

$('#imagepreview').remove();

As I'm assuming your IDs are unique :)

Alex Barrett
A: 

It looks like you are adding the URL to the image AFTER you have appended it to your container. And also the new image you are adding, is it supposed to have an id of "imagepreview"?

'onComplete' : function(response)
{
        var img = new Image();
        $(img).load(function()
        {
                $("#imagepreview").remove();
                $(this).attr({'src':response, 'id': 'imagepreview'});
                $('#imagecontainer').append(this);
                $(this).fadeIn();
        });
}
fudgey