kate_hudson kate_hudson - 1 year ago 63
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?


Answer Source

Try to .get() the image:

  .done(function() { 
    alert("Image " + image_url + " is found!");
  }).fail(function() { 
    alert("Image " + image_url + " was not found.");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download