Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to refresh an image after an ajax file upload in jQuery?

Tags:

jquery

ajax

image

I have an image on the page. I'm using the AJAX form plugin to upload a single image, and after the photo has uploaded I'd like to refresh the image that is already on the page.

$("#profilePicForm").ajaxForm(function() { 
    alert("Photo updated");
    $("#newPhotoForm").slideToggle();
    $("#profilePic img").load(function() {
        $(this).hide();
        $(this).fadeIn('slow');
    }).attr('src', '/Content/UsrImg/Profiles/PhotoName.jpg');
}); 

The newly uploaded file has the same name as the old one, all that is needed is a way to refresh the image. Since it is the same name, cache is getting in the way - the method described in this article didn't work.

Any ideas?

like image 722
Chaddeus Avatar asked Jul 12 '10 11:07

Chaddeus


1 Answers

The article you linked isn't working here, but you can break the cache with a query string on the image, like this:

$("#profilePicForm").ajaxForm(function() { 
  alert("Photo updated");
  $("#newPhotoForm").slideToggle();
  $("#profilePic img").load(function() {
    $(this).hide();
    $(this).fadeIn('slow');
  }).attr('src', '/Content/UsrImg/Profiles/PhotoName.jpg?' + new Date().getTime());
}); 

This forces the browser to check for the image again, since the timestamp is being adding to the query string, it's different every time. This means the browser just can't trust the cache anymore, since that's a slightly different server request...so it'll result in a re-fetch like you want.

like image 137
Nick Craver Avatar answered Oct 17 '22 03:10

Nick Craver