In the code below, I have a function counter which counts element. I use the counter function in order to count the elements that I have in the JSON file. My question is how can I get the value of the counter after the $getJSON, and why when I console log the counter outside of the brackets I keep on getting undefined, why it does not remember the last value, while if I console log the counter inside the brackets I get the number of elements in the JSON file. I want to get the number of elements so afterwards I can use that number in the for loop below.
// global variables
var c = 0;
var a;
var b;
// counter function
function counter() {
return c++;
}
// document ready function
$(document).ready(function () {
$.getJSON("https://graph.facebook.com/v3.2/...", function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
console.log(a) //here I get the number of elements inside the JSON file
});
});
console.log(a) //but if I put the console log here, I get undefined instead of the number
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= a; b++) { //here I want to use what the function returns, so if I have 10 elements in the JSON file I can create 10 div elements in the HTML, it works only if I put number instead of 'a' but I want to use 'a' so I do not have to count the elements as well, the elements will increase.
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>