Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'length' is null or not an object? IE 8

I get the following error in IE8:

length is null or not an object

Anyone have any ideas? Feedback greatly appreciated.

function refresh() {
  $.getJSON(files+"handler.php?action=view&load=update&time="+lastTimeInterval+"&username="+username+"&topic_id="+topic_id+"&t=" + (new Date()), function(json) {
    if(json.length) {
      for(i=0; i < json.length; i++) {
        $('#list').prepend(prepare(json[i]));
        $('#list-' + count).fadeIn(1500);
      }
      var j = i-1;
      lastTimeInterval = json[j].timestamp;
    }
  });
}
like image 793
Scarface Avatar asked Jul 19 '10 19:07

Scarface


People also ask

Is null or not an object?

In JavaScript , null is not an object; and won't work. You must provide a proper object in the given situation. We can resolve this type of issues by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.

Do objects in JS have length?

The length property is used to get the number of keys present in the object. It gives the length of the object.

Why the object is null?

null is a primitive value that represents the intentional absence of any object value. If you see null (either assigned to a variable or returned by a function), then at that place should have been an object, but for some reason, an object wasn't created.


2 Answers

Just check for the object being null or empty:

if (json && json.length) {
  // ...
}

C'mon gang this was glaringly obvious :-)

like image 160
Pointy Avatar answered Oct 21 '22 12:10

Pointy


JSON objects (returned by jQuery or otherwise) do not have a length property. You'll need to iterate over the properties, most likely, or know the structure and simply pull out what you want:

$.getJSON( ..., ..., function( json ) {
  for( var prop in json ) {
    if( !json.hasOwnProperty( prop ) ) { return; }
    alert( prop + " : " + json[prop] );
  }
} );

Alternatively, grab a library like json2 and you'll be able to stringify the object for output/debugging.

like image 1
rfunduk Avatar answered Oct 21 '22 13:10

rfunduk