Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Uncaught TypeError: cannot read property 'length' of null" in jQuery

I'm defining the following action to happen when pressing a button on my HTML:

$(document).ready(function() {
  $("#query").keydown(function () {
    // stuff
    $.get(url, function (result) {
    console.log(result);

    var list = "";

    for (var i = 0, l = result["results"].length; i < l; i++) {
      list += '<li>' + result["results"][i]["label"] + '</li>';
    }

    list = "Here are some results: <ul>" + list + "</ul>";

  });
});

What arrives in "result" is a JSON array in the following form:

{"results":[{"label":"something"},{"label":"something else"},{"label":"many other ones"}]}

So, why is my reference to length being interpreted as a reference to the property of a null value?

like image 815
jl.lykon Avatar asked Dec 04 '13 22:12

jl.lykon


1 Answers

I believe you are getting a json input. You forgot to convert the json into an actual Javascript Object. You can do so with one of the two following ways.

$(document).ready(function() {
  $("#query").keydown(function () {
  // stuff
    $.get(url, function (result) {
    result = JSON.parse(result);
    console.log(result);

    var list = "";

    for (var i = 0, l = result["results"].length; i < l; i++) {
      list += '<li>' + result["results"][i]["label"] + '</li>';
    }

  list = "Here are some results: <ul>" + list + "</ul>";

});

Or

$(document).ready(function() {
  $("#query").keydown(function () {
  // stuff
    $.getJSON(url, function (result) {
    console.log(result);

    var list = "";

    for (var i = 0, l = result["results"].length; i < l; i++) {
      list += '<li>' + result["results"][i]["label"] + '</li>';
    }

  list = "Here are some results: <ul>" + list + "</ul>";

});
like image 88
Kevin Pei Avatar answered Oct 27 '22 05:10

Kevin Pei