"Uncaught TypeError: cannot read property 'length' of null" in jQuery
javascript, jquery, json
Solution
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>";
});
Problem
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?