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.
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>');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With