Hi Guys I have a problem to make a accordion menu (Nested) in Apache Cordova. I have to function with two getjson to get categories and sub categories. Middle of first function i call second function to get sub Categories,But Second Function Did not return my favorite string that is contains htmlSubCategories and it returns undefined value
//Function 1
var Categoriesdata = [];
function getCategories()
{
var htmlCategories = "";
$.getJSON('http://example.com/Categories', null, function (Categoriesdata) {
for (var i = 0; i < Categoriesdata.length ; i++)
{
{
htmlCategories += "<li>";
htmlCategories += "<a href='#'> " + Categoriesdata[i].Text + "</a>";
htmlCategories += getCategoriesRev(Categoriesdata[i].Id);
htmlCategories += "</li>";
}
}
$(".Categories").html(htmlCategories);
});
}
//Function 2
function getCategoriesRev(Id)
{
var htmlSubCategories = "";
$.getJSON('http://example.com/CategoriesRev', { id: Id }, function (CategoriesdataRev) {
if (CategoriesdataRev.length > 0)
{
for (var j = 0; j < CategoriesdataRev.length; j++) {
htmlSubCategories += "<li>";
htmlSubCategories += "<a href='#'> " + CategoriesdataRev[j].Text + "</a>";
htmlSubCategories += getCategoriesRev(CategoriesdataRev[j].Id);
htmlSubCategories += "</li>";
}
htmlSubCategories = "<ul class='submenu'>" + htmlSubCategories + "</ul>";
}
return htmlSubCategories;
});
}
AJAX requests are asynchronous, meaning the second call will not be finished by the time it returns and
htmlSubCategories
will still be an empty string.In JavaScript, you write asynchronous code using callbacks or Promises. Luckily, AJAX requests done with jQuery return you a Promise which you can use.
I would also advise against one AJAX call for each sub category you have. I would only call it once to get all, then filter with JavaScript.
But working with what you have now, the following solution uses simple jQuery: