Search code examples
jqueryajax

Cannot read property error using Ajax & iRail API


So I am using the iRail API (api.irail.be). I want to use it in JQuery using Ajax.

$.ajax({
  method: "GET",
  url: "https://api.irail.be/stations/?format=json",
}).done(function(res) {
  console.log(res['0'].standardname)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This is the code I'm using, but I get an error that standardname is not defined and can't be read


Solution

  • The issue is because the standardname property is within the objects held in the station array. Therefore your logic should be:

    $.ajax({
      method: "GET",
      url: "https://api.irail.be/stations/?format=json",
    }).done(function(res) {
      console.log(res.station['0'].standardname); // note res.station here
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>