I'm new to working with AJAX, but I've been researching it for the past two hours to help in my scenario. I haven't made any progress. :(
Regardless, my issue is that the subPages array is out of scope when I'm outside $.get(...). I've tried using when() and done() for my code, but just can't get it right still.
I think the problem lies within the iterations going through a for loop since I have pages[i] in multiple sections of my code being used. That's why I can't use when() and done() when needed.
Here's what I have:
var subPages = [];
var containsSub = '/sites/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
}
});
// subPages array is loaded with the correct values
console.log("subPages inside get: " + subPages);
});
// empty here
console.log("subPages outstide all: " + subPages);
Edit: With the addition of the then chain and code, I'm having an undefined for subPages[i]
var subPages = [];
var containsSub = '/sites/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
//console.log("<a href='"+ this.href + "'>" + this.href + "</a>" + " <br>");
}
});
console.log("subPages inside get: " + subPages);
})
.then(function(){
console.log("subPages outstide all: " + subPages);
// print bold for current main page
tempString += "<strong><a href='"+ baseURL + pages[i] + "'>" + pages[i].substr(27,pages[i].length) + "</a><strong>" + " <br>";
for(var i = 0; i < subPages.length - 1; i++){
console.log("<a href='"+ subPages[i] + "'>" + subPages[i] + "</a>" + " <br>");
}
subPages = [];
pages.splice(i, 1);
})
}
11/25 Edit: I fixed the issue below with my answer by removing some complications and decided that an AJAX request was more in logic.
var subPages = [];
var containsSub = '/sites/it/InfoProtect/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.ajax({
url: baseURL + pages[i],
async: false,
success: function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
}
});
}
})