andyderuyter andyderuyter - 1 month ago 6
Javascript Question

Update div with new image only when user uploaded new image

I have two separate pages: one where user uploads new image, other where that images is loaded inside a div through ajax.

The script is looking at filenames inside a txt file and only the first filename is being fetched (file_name2.jpg|file_name1.jpg)

Here is the script:

$(function(){
var GALLERY = {
container: "#gallery",
url: "getImages.txt",
delay: 10000,
load: function(){
var _gallery = this;
var number = 1 + Math.floor(Math.random() * 9999999999);
$.ajax({
type: "get",
url: this.url + '?rand=' + number,
beforeSend: function(){
$(_gallery.container).find('img').remove();
},
success: function(data){
var images = data.split('|', 1);
$.each(images, function(){
_gallery.display(this);
});
},
complete: function(){
setTimeout(function(){
_gallery.load();
}, _gallery.delay);
}
});
},
display: function(image_url){
$('<img />').attr('src', 'images/' + image_url).load(function(){
$(this);
}).prependTo(this.container);
}
}
GALLERY.load();
});


The problem is: The script always executes and replaces the image, even when no new image was uploaded.

Ideal the image should only refresh when a new image was uploaded.

How can I achieve this behavior?

Answer

You need to store result data in a variable or like GALLERY.lastdata then the setTimeout will request another and see if new data is the same the image won't refresh.

$(function(){
    var GALLERY = {
        lastdata : "",
        container: "#gallery",
        url: "getImages.txt",
        delay: 10000,
        load: function(){
            var _gallery = this;
            var number = 1 + Math.floor(Math.random() * 9999999999);
            $.ajax({
                type: "get",
                url: this.url + '?rand=' + number,
                success: function(data){
                       //detect new images
                      if(_gallery.lastdata != data){
                var images = data.split('|', 1);
                $.each(images, function(){
                          _gallery.lastdata = data;
                         _gallery.display(this);
                });
                       } 

                },
                complete: function(data){
                    setTimeout(function(){
                       _gallery.load();
                    }, _gallery.delay);
                }
            });
        },
        display: function(image_url){
            $('<img />').attr('src', 'images/' + image_url).load(function(){
                $(this);
            }).prependTo(this.container);
        }
    }
    GALLERY.load();
});
Comments