0

I was making a preloader using Ajax but It seems not to work. I want to load an image that if It's there the success does something -alert something-, but if It's not there just the error does another thing -alert another text-, but in this code It doesn´t matter if the image is found or not, both alerts happen no matter what, I mean if the image is found both alerts happen, but if I delete the photo both alerts happen as well, what could be the way to achieve this guys with ajax's complete and error? Thanks for any guideline in this one.

function preloadImages()
{   
 var $image = 'http://www.mysite/images/example.jpg';
 jQuery.ajax({
    url: $image,
            complete: function(){
         fileLoaded();
     },
    error: function(){
        errorLoading();
    }
 });    
}

function fileLoaded(){
alert('There is the image');
}

function errorLoading(){
alert('No image');
}

Thanks for any help in advance. Greetings.

A J
  • 2,112
  • 15
  • 24
Diego
  • 561
  • 1
  • 7
  • 18

2 Answers2

1

Change complete to success

jQuery.ajax({
 url: $image,
     success: function(){
     fileLoaded();
 },
error: function(){
    errorLoading();
}
});

Fiddle

Shijin TR
  • 7,516
  • 10
  • 55
  • 122
  • Hi shijin, If I use ´success´ a funny thing is now happening, the ´No Image´ alert happens when actually the photo is there or if it's no there. – Diego Mar 26 '14 at 07:51
1

Try to figure out the error out of it as in this SO answer

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

If the image is in the site directory do it the following way

    var image = '../Images/Slider/1.jpg'; // give in the src of the image
    $.ajax({
        type: 'GET',
        url: image,
        success: function (bytes) {
            alert('in');
        },
        error: function () {
            alert('Error!!!')
        }
    });
Community
  • 1
  • 1
A J
  • 2,112
  • 15
  • 24
  • Hi, If I leave the two double quotation marks FireBugs says that there is a syntax error, but if I change the first marks for single quotation marks the alert happen but there is like a blank alert, I mean no text or anything in the alert box. – Diego Mar 26 '14 at 08:05
  • Btw console.log(err.Message) says: Undefined. – Diego Mar 26 '14 at 08:16
  • 1
    I m trying it out myself too .. are you trying any cross-domain ajax? – A J Mar 26 '14 at 08:22
  • try giving in the image's src – A J Mar 26 '14 at 08:34
  • Man the problem was that I was looking for an image from another site with the whole http://, but using a relative path with ../images/ -as you suggested- It did the trick. Thanks a lot AJ. Have a nice day. – Diego Mar 26 '14 at 08:50