I’ve been trying to return the count of my json result, without success. The problem is, the number always returns, but it’s wrong.
Wondering how I can return a basic counter of all the results return from the AJAX result.
Example
The API returns 100 posts, but the code below returns 42
var counter = x.length;
console.log(counter + ' items'); //42 items
Code - slightly reduced for viewing:
(function(){
var x = 'https://jsonplaceholder.typicode.com/posts'; //100 posts
var photoCall = $.ajax({
dataType: 'jsonp',
url: x
});
photoCall.done(function(data) {
var template = $('#results_tpl').html();
var html = Mustache.render(template, data);
$results.html(html);
var counter = x.length;
console.log(counter + ' items');
});
})();
Do I need a different approach, any ideas how I can get this to work?
Maybe it is ‘data’ that you want to count. What format is data in, is it an array? You can console.log it to see what it is. If it’s an array of results then data.length should do.
I’ve tested above with a sample api that uses an array without any parent keys. I have been using another json response which has an array but with a couple of parents which returns: