skip to Main Content

Using Ajax, I check if two image sources are available on the server or not. The Ajax code is the following:

        if (result['img_one'] !== '') {
            var src_one = "blah-blah-one.jpg";
            $.ajax({url: src_one,
                success: function(data, textStatus) {
                    $("#profile-box").show();
                    $("#profile-img").attr("src", src_one);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#profile-box').hide();
                }
            });
        }
        if (result['img_two'] !== '') {
            var src_two = "blah-blah-two.jpg";
            $.ajax({url: src_two,
                success: function(data, textStatus) {
                    $("#profile-box").show();
                    $("#profile-pic").attr("src", src_two);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#profile-box').hide();
                }
            });
        }

After these two blocks of code, I want to check if both of images are available and loadable or not. However, being a newbie, I cannot do it. Using $.when and .done did not help me, and the problem still preserved. I tried many different ways and various techniques to check if the images exist on the server, however, when checking if both of them are available, I ran into problem. In other words, I can check if each and every image exists, yet when I want to take another action when both of them are available, I get stuck. May you please help.

Even the following functions did not help:

function checkImage(url){

    var image = new Image();

    image.src = url;

    if (!image.complete) {
        return false;
    }
    else if (image.height === 0) {
        return false;
    }

    return true;
}

and

function imageExists (src) {
    var result;
    $("<img>").attr('src', src).on("error", function(e) {
             result =  false;
        })
        .on("load", function(e) {
            result = true;
        });
    return result;
}

2

Answers


  1. That’s not really possible the way you’re using asynchronous functions.

    One way is with Promises. Here’s a function that loads an image (provided a URL in src) and returns a promise to do so:

    function loadImage( src, imgSelector ) {
      return new Promise(function(resolve, reject) {
        $(imgSelector).attr('src', src).on("error", function(e) {
          reject( "Unable to load " + src )
        })
        .on("load", function(e) {
          resolve()
        });
      })
    }
    

    Then you can ask to load two images, and let you know when they’re done:

    Promise.all( [loadImage('first.jpg', '#profile-img'), loadImage('second.jpg', '#profile-pic') ] ).then(
      function(result) {
        console.log("Got 'em all!'")
      }
    ).catch(function(result) {
      console.log( "Oops, error: " + result )
    })
    

    When they’ve both loaded, the “Got ’em all!” message should show in the console. If any fails to load, it will trigger the “Oops, error” message.

    Login or Signup to reply.
  2. You probably want to nest the ajax calls. Because ajax calls are asynchronous, the browser will not “wait” for the first one to complete before calling the second one. So the pseudocode would look something like this:

    ajax(
      {
        url: src1,
        success: function (result) {
           ajax(
             { 
               url: src2,
               success: function (result) {
                 // At this point both images are loaded
                 box.show();
               }
             }
           )
         }
       }
    )
    

    A more “modern” approach would be to use Promises or async/await, but this will probably get you what you need using jQuery.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search