0

Peace and Blessing be Upon us all.

Basically I have a div say:

<div class="divele" style="background: url("/image/bkimg.jpg") top center no-repeat;background-size:cover;"></div>

Then I have an upload button which the user can select an image from his/her computer and save it in the database. After the XHR response with file being saved. The server respond with the new image link the same as /image/bkimg.jpg which this time the old image has replaced with the new uploaded one. Now I need the div to re-request the new image from the server. and this is what i'm doing:

var parts = result;
$('.divele').css({"background": "url("+parts+") top center no-repeat", "background-size": "cover"});

Don't really know why But this does not load the new image.

Much regards

Mr. Nobody
  • 89
  • 1
  • 9
  • If you inspect the div with your browser's dev tools, if there is an error you should see something there. Also you can check the "Network" tab to verify if/how the image is requested. – Hugues M. May 07 '17 at 11:49
  • This will work fine with image tag but with background we need full path if using inline. Check with background-image property – Deepak Dholiyan May 07 '17 at 11:51
  • Hope this will help you:- http://stackoverflow.com/questions/34119048/change-a-background-image-through-a-file-input – Deepak Dholiyan May 07 '17 at 11:54
  • Okay I figured it out, Because the both new and old link is the same as `/image/bkimg.jpg/`. It does not request the new image. Do you know how to force request the new image? – Mr. Nobody May 07 '17 at 11:57
  • Add a cache buster to the end. Image.png?buster123456 – rlemon May 07 '17 at 12:18
  • Add a dummy query parameter onto the image URL so that it gets treated as a new image instead of using the cached version. e.g. `"background": "url(" + parts + "?" + new Date().getTime() + ")"`... – mikej May 07 '17 at 12:19

1 Answers1

0

Thanks to this Answer: How to reload/refresh an element(image) in jQuery

Which Explains because both names are the same the browser uses the cached version, which in order to fix it you can simply add an extra unnecessary parameter which will look like:

d = new Date();
$('.divele').css({"background-image": "url("+result+"?"+d.getTime()+")"}); 
Community
  • 1
  • 1
Mr. Nobody
  • 89
  • 1
  • 9