kate_hudson kate_hudson - 3 months ago 6
jQuery Question

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

Answer

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.");
  });
Comments