kate_hudson kate_hudson - 6 months ago 24
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();

type: "get",
url: "./getImage",
data: {
year : selectedYear,
product : selectedProduct,
image : selectedImage
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?



Try to .get() the image:

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