katie hudson
katie hudson

Reputation: 2893

Determine if image available

I make an Ajax call to get an image path

var triggerImageChange = function() {
    var selectedYear = $("#year2 option:selected").val();
    var selectedType = $("#type2 option:selected").val();
    var selectedImage = $("#imageSelect2 option:selected").val();

    $.ajax({
        type: "get",
        url: "./getImage",
        data: {
            year : selectedYear,
            product : selectedProduct,
            image : selectedImage
        }
    }).done(function(data){
        var url = $('meta[name="base_url"]').attr('content');

        if(data) {
            $('#comparisonImage').attr('src', '');
            $('#comparisonImage').attr('src', url + data);
            $('#comparisonImage').css('display', 'block');
        }
    });
};

Now data will always return a path. I then use this path to set the image src attribute. Just because a path is returned however does not mean that an image is present at that location. If an image is not available I need to display a default image.

Now I dont think I can use the ajax error because as I say, data will always return a path. I was wondering how I could determine if an image is available once I attempt to set it as the src attribute?

Thanks

Upvotes: 0

Views: 34

Answers (1)

Nick Bull
Nick Bull

Reputation: 9866

Try to .get() the image:

$.get(image_url)
  .done(function() { 
    alert("Image " + image_url + " is found!");
  }).fail(function() { 
    alert("Image " + image_url + " was not found.");
  });

Upvotes: 1

Related Questions