EDIT: I know this question has been asked before and examples say to put your second ajax request in the "success" section of the first. However, even when i do that it still returns undefined
I am making an AJAX Request to a Wordpress Rest API, but one of the API results i need (featured image URL) is not directly linked in the first set of results. Instead, only its wordpress ID is linked, which then needs to be plugged into a second AJAX URL to get the actual link to the image.
So essentially I'm trying to pull the ID number from my first request and plug it into the URL for my second request, then get the results and pass them back to the first function to be displayed with the rest of the data.
I know that because AJAX is Asynchronous, my featured image link is coming back as "Undefined" because the request is firing asynchronously instead of going in sequence after the first request. I tried embedding my second AJAX request directly into the "success" field of the first request, but it still came back undefined. Here's the code as it stands now (disregard some of the inner details about shortening the titles and such)
" postFeatMedia(result[i].featured_media) " is what is coming back as undefined:
function postFeatMedia(postFeatMediaId){
if(featMedRequest) {
featMedRequest.abort();
}
featMedRequest = $.ajax({
async: true,
url: blogURL + "/wp-json/wp/v2/media/" + postFeatMediaId,
contentType: "application/json",
dataType: "json",
success: function(result){
for(var i=0; i < result.length; i++){
result[i].guid.rendered;
}
}
});
}
function postPreview(){
prevContainer.each(function(){
if(prevRequest) {
prevRequest.abort();
}
prevRequest = $.ajax({
async: true,
url: blogURL + "/wp-json/wp/v2/posts?per_page=" + prevCount,
contentType: "application/json",
dataType: "json",
success: function(result){
for(var i=0; i < prevCount; i++){
if (result[i].featured_media > 0) {
var firstImg = postFeatMedia(result[i].featured_media);
alert ('featured media found, url is: ' + postFeatMedia(result[i].featured_media));
}
else if (!result[i].featured_media && $(result[i].content.rendered).find('img:first').length > 0) {
var firstImg = $(result[i].content.rendered).find('img:first');
alert ('no featured media, first image found');
}
else {
var firstImg = 'none';
alert('no images found');
}
var prevDate = result[i].date.slice(5,7) + "/" + result[i].date.slice(8,10) + "/" + result[i].date.substr(0,4);
var titleLimit = 46;
var shortTitle = result[i].title.rendered.substr(0,titleLimit);
if (result[i].title.rendered.length > titleLimit){
var shortTitle = result[i].title.rendered.substr(0,titleLimit) + "...";
}
prevContainer.append(
"<a class='prevItem' href='#blog.html?postid=" + result[i].id + "'>" +
"<span class='prevDate'>" + prevDate + "</span>" +
firstImg[0].outerHTML +
"<h3>" + shortTitle + "</h3>" +
"</a>"
);
}
}
});
});
};