Ayan Bera
Ayan Bera

Reputation: 80

AJAX not loading images properly

I have page where the user can change his profile picture. Now by any chance if the user operates from multiple browsers at the same time, I want to change the picture in all of them. Wrote the ajax call but somehow all browsers (IE11, FF30, etc.) are loading the image from the cache.

function ref() {
                //$('#logout>div').fadeOut(300).load(location.href+' #logout #dp').fadeIn(300);
                $.ajax({
                    url     :   '<?php echo base_url(); ?>uploadimg/refresh/'+Math.random(),
                    type    :   'POST',
                    cache   :   false,
                    success :   function(data) {
                        $('#logout #dp').fadeOut(100).attr('src','<?php echo base_url(); ?>assets/uploads/'+data).fadeIn(100);
                        //alert('a');
                    }
                });

                setTimeout(ref, 6000);
        }

Upvotes: 1

Views: 92

Answers (2)

AsgarAli
AsgarAli

Reputation: 2211

Math.random() return a number with decimal point.

So I would suggest that use a number without any special chars.

 function ref()
{
    $.ajax({
        url: '<?php echo base_url(); ?>uploadimg/refresh/' + Math.random(),
        type: 'POST',
        cache: false,
        success: function (data) {
            d = new Date();
            $('#logout #dp').fadeOut(100).attr('src', '<?php echo base_url(); ?>assets/uploads/' + data + "?" + d.getTime()).fadeIn(100);
        }
    });
    setTimeout(ref, 6000);
}

Upvotes: 0

Andy Noelker
Andy Noelker

Reputation: 11269

Even if the html image src is getting constantly rebuilt, if the text of that source stays the same, your browser will cache the actual image resource until the page has been reloaded. You can add a ? followed by a random string to the end of your image source and that should force the browser to refresh from the source.

Inside your success:

$('#logout #dp')
    .fadeOut(100)
    .attr('src','<?php echo base_url(); ?>assets/uploads/' + data + '?' + Math.random())
    .fadeIn(100);

Upvotes: 1

Related Questions