Question

I am using jQuery File Upload for PHP and it works well. The only problem is that when I open two tabs in the browser of the same page (index.html) and I upload a photo in tab 1 and I see the uploaded photo but when I go to tab 2 there is no the uploaded photo. I have to refresh the page to see it.

So I tried to solve the problem in this way:

setInterval(function() {
    $.ajax({
    url: $('#fileupload').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done').call(this, $.Event('done'), {
            result: result
        });
    });
}, 3000);

Works but not very well. Every three seconds I get all uploaded images repeated (not the one I just uploaded). I also tried to remove all list of images $("ul.files").find('.template-download').remove(); and then add them so in this way the images are not repeated. But as I said doesn't work very well.

Any help is appreciated. Thank you!

Was it helpful?

Solution

You are uploading photos in every tab every 3 seconds?? You are aware that that's just a waste of bandwidth and server processing, right?

Of course your images get repeated, because to the server, every time this code executes is a new image. Wouldn't it be better if you created a method that just refreshes de page? I mean, I suppose you store your uploaded photos in the server (otherwise you wouldn't be able to see them in the other tabs). Just poll the server to know if there are new photos uploaded every three seconds.

Or even better, if you're targeting html5-compliant browswers that support the sessionStorage object, you could add (or update) a property there. Any other tab in the same domain will immediately receive an event that such property was added / modified. You can use this to know when a new image has been uploaded.

//when the image has uploaded...
sessionStorage.setItem('images', 'number-of-images');

And if you have an event handler like this in your page, you'll get notified when this property changes, indicating you can refresh your page and get the new images:

window.addEventListener('storage', function(e) {
    if (e.key == 'images') { //key 'images' updated.
         //refresh page via AJAX.
    }
}, false);

Ideally, you would use this method if sessionStorage is available, and default to polling the server if it is not:

if (window.sessionStorage) { 
     //sessionStorage support, use the event.
} else {
    //default to polling the web server for updates
}

Hope this helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top