I'm trying to get all task items from all subsites of a SharePoint site and got stuck when trying to get all the responses into one global array for further processing. The array gets filled but when you try te get the element it shows undefined.
var TaskList = [];
$(document).ready(function() {
Main();
});
function Main (){
var SiteUrl = _spPageContextInfo.webAbsoluteUrl;
var main = $("#main");
function GetListItems (TragetUrl){
$.ajax({
url: SiteUrl + "//" + TragetUrl + "/_api/web/lists/getbytitle('Tasker')/items?$select=Title,Status,StartDate,Status,DueDate",
type: "GET",
data: JSON.stringify({ '__metadata': { 'type': 'SP.Data.TestListItem' }}),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(d) {
// TaskList.push(d.d.results)
$.each(d.d.results, function(idx, Task){
console.log(Task['Title']);
TaskList.push(Task);
});
// return TaskList;
},
error: function() {console.log('failed to get');}
});
}
function GetSubsites (BaseUrl){
$.ajax({
url: BaseUrl + "/_api/web/webs?$select=Title",
type: "GET",
data: JSON.stringify({ '__metadata': { 'type': 'SP.WebCollection' }}),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(d) {
console.table(d.d.results);
//process Subsites
$.each(d.d.results, function(idx, subsite){
console.log(subsite["Title"]);
GetListItems(subsite["Title"]);
});
},
error: function() {console.log('fail');}
});
}
GetSubsites(SiteUrl);
console.log(TaskList); //array output apears normal
console.log(TaskList[0]); //undefined
console.log(TaskList.length); // length is 0
}
Thanks.