0

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>"
          );
        }
      }
    });
  });
};
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Rico
  • 1
  • 1
  • Does this answer your question? [jQuery Ajax Request inside Ajax Request](https://stackoverflow.com/questions/10089447/jquery-ajax-request-inside-ajax-request) – Liam Dec 24 '21 at 10:51
  • `postFeatMedia` function does not have a `return` statement so that's why it's undefined. Even if you returned the request it will give you a jQuery XMLHttpRequest object and not the actual value you are looking for. This has to do with JS being having non blocking I/O. If you call an http request it just makes the request and keeps executing. Whatever you want to do with the result of `featMedRequest` you need to do inside its `success` callback (so all the things you do with `firstImg` you need to do inside the second http call and not the first). – Federico Rodríguez Dec 24 '21 at 20:38
  • @FedericoRodríguez I've changed things around so that the firstImg functions are inside the other call, and all the needed results are passed from the first call into the second through function arguments. My "undefined" console error has gone away, and shows no errors, but still isn't displaying my results. Right now it's set up in this way: https://jsfiddle.net/0jg38zLt/ Oddly, i have another page that is doing almost the same thing for a different blog and it works, that (working) code is here: https://jsfiddle.net/vadL9ojs/ Not sure why one works and not the other. – Rico Dec 25 '21 at 10:48

0 Answers0