kieran
kieran

Reputation: 3

Handling undefined error JQuery GetJson

I am using getJSON() to query an online plane image database and return a link and image url. My issue is that if the item is not in the database, I will get this error on the console:

Cannot read property '0' of undefined.

I have used var error = res.status with

if (error == "404") {   
    $("#image").attr('src', "placeholder.jpg");
}

to show the default image for when there is no picture but it does not work. Here are the two examples of responses from the server:

Error:

{"status":404,"error":"Aircraft thumbnail not found."}

Image in database:

{"status":200,"count":1,"data":[{"image":"http:\/\/www.airport-data.com\/images\/aircraft\/thumbnails\/001\/369\/001369561.jpg","link":"http:\/\/www.airport-data.com\/aircraft\/photo\/001369561.html","photographer":"magnaman"}]}

My question is how can I get around the undefined error or display the default image if it is not in the database

Thanks in advance

  var imgUrl
$.get('http://192.168.1.64:8080/VirtualRadar/AirportDataThumbnails.json?icao='+value.Icao, function(res) {
    var imgUrl = res.data[0].image
    var error = res.status
    var imgHref = res.data[0].link

    if (error == "404") {
        $("#image").attr('src', "placeholder.jpg");
    } else {
        $("#image").attr('src', imgUrl);
                $("#image2").attr('src', imgUrl);
                $("#imageurl").attr('href', imgHref);
    }
})

Upvotes: 0

Views: 60

Answers (1)

Barmar
Barmar

Reputation: 780974

When there's an error, there's no res.data property. You should only access this in the else block.

$.get('http://192.168.1.64:8080/VirtualRadar/AirportDataThumbnails.json?icao=' + value.Icao, function(res) {
  var error = res.status;
  if (error == "404") {
    $("#image").attr('src', "placeholder.jpg");
  } else {
    var imgUrl = res.data[0].image;
    var imgHref = res.data[0].link;
    $("#image").attr('src', imgUrl);
    $("#image2").attr('src', imgUrl);
    $("#imageurl").attr('href', imgHref);
  }
})

Upvotes: 2

Related Questions