CodeOverRide
CodeOverRide

Reputation: 4471

Display loading GIF image while loading with AJAX

   $.ajax({
        url: "/image/productImages.jpg",
        timeout:5000,

        beforeSend: function(){
    // Handle the beforeSend event
        $('##loading').show();
        },

        complete: function(){
        // Handle the complete event
        $('##loading').hide();
        },

        success: function (data) {
            alert("image was added successfully");
        },

        error: function () {
            alert("There was an error. Image could not be added, please try again");
        }
    });

I'm want to show display loading gif while image is loading and then remove it once image is loaded. Here I have this code to do that but, this is going straight to error. does anyone have any idea why or how to fix this. Thanks in advance!

Upvotes: 1

Views: 7091

Answers (3)

CodeOverRide
CodeOverRide

Reputation: 4471

so I found out that you cannot load image as url in .ajax tag. thanks for the response but ##loading is just for the coldfusion tags

.load() is recommended like this:

 var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
                  .load(function() {
                     if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                         alert('broken image!');
                     } else {
                         $("#something").append(img);
                     }
          });

However, this also breaks my code I have implemented and doesn't work in IE...unfornately.

Upvotes: 0

Kevin B
Kevin B

Reputation: 95030

If you are getting to the error handler, the error is going to be related to the data that is being returned by the server. Try this as the error handler to get more information about what is going on (view the result in the browser's console):

error: function (x,y,z) {
    alert("There was an error. Image could not be added, please try again");
    console.log(x,y,z);
    //alert(x + "\n" + y + "\n" + z);
}

However, there is an easier way to pre-load an image. Try this:

$("#loading").show();
var img = new Image();
$(img).load(function(){
    $("#loading").hide();
});
img.src = "/image/productImages.jpg";

Upvotes: 1

Gabe
Gabe

Reputation: 50473

Your id selector has two hashes,

Try this instead:

 $('#loading').show();

Upvotes: 3

Related Questions