6

I need force to div background image refresh while my ajax request success My div background image url same not change but image content change while ajax success.how can i refresh background url.

JavaScript

    $.ajax({
 url: "editor/savemapimage.php",
 type:"POST",
 data:{imagevalue : urlimage},
success:function(data){$(".map_canvas").css("background-image","url("+data+")");},

Above code if result data is string something map.png so this would be same but my php page update image content so need refresh this url every time while image update.

Affan Ahmad
  • 451
  • 4
  • 9
  • 22
  • You have to edit image url like here: http://stackoverflow.com/a/2104998/3090180 – apo Dec 11 '13 at 12:57

3 Answers3

18

You can add an unique ID to the end of the image url like:

http://yourdomain.jpg?random=1239308234

If the ID is unique the browser will consider it a new resource and will reload the image.

const randomId = new Date().getTime();
$.ajax({
    url: 'editor/savemapimage.php',
    type: 'POST',
    data: {
        imagevalue: urlimage
    },
    success: function (data) {
        $('.map_canvas')
            .css('background-image', `url(${data}?random=${randomId}`);
    },
);
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
  • Thanks! IF you do not want that query string on there then change to that random string then remove it again. $(".map_canvas").css("background-image", "url(" + data + ")"); – Adamz May 16 '21 at 22:13
0

You should add some random query to your background image and set it again

$.ajax({
    url: "editor/savemapimage.php",
    type:"POST",
    data:{imagevalue : urlimage},
    success:function(data){$(".map_canvas").css("background-image","url("+data+"?random="+ new Date().getTime()));},
Ruben Nagoga
  • 2,178
  • 1
  • 19
  • 30
0

For anyone working with Literally Canvas you may get this same issue. It was certainly occurring for me in Chrome. Bas van Dijk's solution works well so just use it like so:

$(document).ready(function() {

    //background image (add random variable to stop caching)
    var backgroundImage = new Image()
    backgroundImage.src = "my-image.png?r=" + new Date().getTime();

    var lc = LC.init(
        document.getElementsByClassName('literallycanvasdiv')[0],
        {
            backgroundColor: 'whiteSmoke', 
            backgroundShapes: [LC.createShape('Image', {x: 10, y: 10, image: backgroundImage, scale: 1})]
        }
    );
});
garrettlynchirl
  • 790
  • 8
  • 23