Ajax Uncaught TypeError: Unable to read property 'length' of

advertisements

I want to populate my select box with json data from an external url.

I keep getting

Uncaught TypeError: Cannot read property 'length' of undefined

below is my json response

{"ecoachlabs":{
  "status":"201",
  "msg":"Form data loaded successfully.",
  "categories":[
    {"id":"2","category":"church"},{"id":"3","category":"financial institution"},
    {"id":"4","category":"old students association"},
    {"id":"1","category":"school"},
    {"id":"5","category":"tertiary"}
  ],
  "storage":[
    {"id":"1","category":"100MB"},{"id":"2","category":"250MB"},
    {"id":"3","category":"500MB"},{"id":"4","category":"2GB"},
    {"id":"5","category":"3GB"},{"id":"6","category":"5GB"}
  ]
  }}

below is my ajax post code

$(document).ready(function() {
  $("#institution_category").click(function() {

    var formData = {
      load_request_form_data: "1"
    }; //Array 

    $.ajax({
      url: "http://api.ecoachlabs.com/v1/requests/api.php",
      type: "POST",
      data: formData,
      success: function(data, textStatus, jqXHR) {
        console.log(data.ecoachlabs.categories); //data - response from server
        $.each(data.categories, function(i, v) {
          $('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {

      }
    });
  });
});


You do a console log of onsole.log(data.ecoachlabs.categories); and then use data.categories. Change data.categories to data.ecoachlabs.categories to parse the object correctly, otherwise you will get undefined. See the working snippet below please:

var formData = {
  load_request_form_data: "1"
}; //Array 

$.ajax({
  url: "http://api.ecoachlabs.com/v1/requests/api.php",
  type: "POST",
  data: formData,
  success: function(data, textStatus, jqXHR) {
    console.log(data.ecoachlabs.categories); //data - response from server
    $.each(data.ecoachlabs.categories, function(i, v) {
      $('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
    });
  },
  error: function(jqXHR, textStatus, errorThrown) {

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='institution_category'>

</select>