Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

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.

like image 856
qqruza Avatar asked Jan 07 '13 16:01

qqruza


1 Answers

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>');
            }
          });
like image 121
DeeDub Avatar answered Oct 10 '22 23:10

DeeDub