qqruza
qqruza

Reputation: 1417

JQuery and Ajax: Cannot read property 'length' of undefined

I am trying to get a particular request from website by using variable in the URL and AJAX to display JSON. It seems like everything is working but there is an error "TypeError: Cannot read property 'length' of undefined". A debugger points to JQuery file and the line in my script ($.ajax.success).

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  alert('Query Variable ' + variable + ' not found');
}

$(document).ready(function () {

  var output = $('#news');
  var postid = getQueryVariable('id');

  $.ajax({
    url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
    async: false,
    callback: 'callback',
    crossDomain: true,
    contentType: 'application/json; charset=utf-8',
    type: 'POST',
    dataType: 'jsonp',
    timeout: 5000,
    success: function (data, status) {
       $.each(data.posts, function (i, item) {
        var news = '<div>' + item.title + '</div><div>' + item.content + '</div><hr/>';

        output.append(news);


      });
    },
    error: function () {
      output.text('There was an error loading the data.');
    }
  });
})

Could you please help me to sort this out? Really appreciate your halp.

Upvotes: 5

Views: 55983

Answers (2)

DeeDub
DeeDub

Reputation: 1662

You should validate your data before performing operations on it:

UPDATED

 $.ajax({
            url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
            async: false,
            callback: 'callback',
            crossDomain: true,
            contentType: 'application/json; charset=utf-8',
            type: 'POST',
            dataType: 'jsonp',
            timeout: 5000,
            success: function (data, status) {
               if(data != undefined && data.post != undefined){
                 $('#news').append('<div>' + data.post.title + '</div><div>' + data.post.content + '</div><hr/>');
                }
            },
            error: function () {
              output.html('<h1 class="error">There was an error loading the data.</h2>');
            }
          });

Upvotes: 5

Rahul
Rahul

Reputation: 988

you applying $.each on data.post which could be undefined if your data is null. $.each expects and array or collection that is why you getting an error for length. since your data is null hence data.post would be undefined. you could check before applying $.each like

if(typeof data == "object" && data.post)
    //Your code here.

this check should be applied whenever you expect some data from ajax.

Upvotes: 1

Related Questions