Karolis Stakėnas
Karolis Stakėnas

Reputation: 758

Ajax request in Javascript for loop

I've stumbled upon a problem I can't seem to 'google' an answer to, nor I am able to find one over here, so I'm asking for someones help.

I'm creating a carousel/swiper. I got an array of TAGS, for each TAG I'm creating a swipe_item. Inside each of swipe_item I'm calling an ajax request for posts, it takes in the TAG and returns up to 5 posts per TAG given.

What I want to achieve is that after I create a swap_item for each TAG, I want to fill each swip_item with its response data. In my case and in my code provided there are two tags, so I'm creating two swipe_items, then, the first swipe_item returns 2 posts, the second swipe_item returns 5 posts. How do I will HTML to each of swipe_item with the posts it returns in the ajax request?

I'm a beginner in Ajax/JSON, please ask if You need any more details or anything else on this matter. Thanks!

Code :

var dataSupertags = {
  div_id: 'supertags',
  jsonData: superTags
};

function drawSupertags(dataSupertags) {

  var el = dataSupertags.div_id;
  var data = dataSupertags.jsonData;

  cnt = " * SUPERTAGS DEMO * ";

  cnt += '<section id="main_carousel1" class="section_style_1 carousel1">';
  cnt += '<div class="carousel1_content">';
  cnt += '<div class="posts" id="carousel1_1" style="visibility:visible;">';
  cnt += '<div class="wrapper">';
  for (i = 0; i < data.length; i++) {
    cnt += '<div class="swipe_item">';
    cnt += '<header class="swipe_list">';
    cnt += '<h1 class="active">' + '<a href="http://zyme.lrytas.lt/' + data[i].titleurl + '">' + data[i].title + '</a>' + '</h1>';
    cnt += '</header>';
    jQuery.ajax({
      dataType: 'json',
      url: 'APIURL',
      data: {
        count: 5,
        ret_fields: [
          'props.title__AS__title',
          'props.comentCount__AS__cc',
          'fb_shares',
          'props.pubfromdate_local__AS__pubdate',
          'props.href__AS__href',
          "props.media[indexof(x.type='media' for x in props.media)].otheralternate.300x200.href__AS__thumb",
        ].join(','),
        type: 'Video,Articolo,Komentaras,Foto,Recipe',
        tag_slugs: data[i].topics[0].slug,
        order: 'pubfromdate-'
      },
      success: function(response) {
        console.info(response);
        console.info(response.result.length);
        var postData;
        for (f = 0; response.result.length > 0; f++) {
          postData += '<div class="post">';
          postData += '<a href="' + response.result[f].href + '" class="img" style="background-image:url("' + response.result[f].thumb + '")"></a>';
          postData += '<div class="desc">';
          postData += '<h2><a href="#">' + response.result[f].title + ' <span>' + response.result[f].fb_shares + '</span></a></h2>';
          postData += '</div>';
          postData += '</div>';
        }
        console.log(postData);
      }
    });
    cnt += '</div>';
    console.log(data[i]);
  }
  cnt += '</div>';
  cnt += '</div>';
  cnt += '<div class="carouselNext carouselButton" onclick="carousel1_1.next()"></div>' + '<div class="carouselPrev carouselButton" onclick="carousel1_1.prev()"></div>';
  cnt += '</div>';
  cnt += '</section>';

  document.getElementById(el).innerHTML = cnt;

  if (jQuery('#carousel1_1').find('div.swipe_item').length > 0) {
    jQuery('#main_carousel1').show();
    window.carousel1_1 = new Swipe(document.getElementById('carousel1_1'), {
      speed: 400,
      auto: 5000
    });
  };

};

drawSupertags(dataSupertags);

   

What would be the correct way to fill every swipe_item that I created with a for loop with posts?

Upvotes: 2

Views: 2734

Answers (2)

Joe
Joe

Reputation: 1885

You are attempting to create your html in one synchronous method, but this is not how AJAX works as it is asynchronous. Your have to wait for your AJAX requests to return something, and they can return in any order.

Instead, try to construct the wrapper html first, and then inject each swipe_item as it's AJAX request is returned.

var dataSupertags = {
  div_id: 'supertags',
  jsonData: superTags
};

function drawSupertagsWrapper(dataSupertags) {

  var el = dataSupertags.div_id;
  var data = dataSupertags.jsonData;

  cnt = " * SUPERTAGS DEMO * ";

  cnt += '<section id="main_carousel1" class="section_style_1 carousel1">';
  cnt += '<div class="carousel1_content">';
  cnt += '<div class="posts" id="carousel1_1" style="visibility:visible;">';
  cnt += '<div class="wrapper" id="' + el + '_wrapper">';
  cnt += '</div>';
  cnt += '</div>';
  cnt += '<div class="carouselNext carouselButton" onclick="carousel1_1.next()"></div>' + '<div class="carouselPrev carouselButton" onclick="carousel1_1.prev()"></div>';
  cnt += '</div>';
  cnt += '</section>';

  document.getElementById(el).innerHTML = cnt;
}

function drawSupertagsItems(dataSupertags) {
    var el = dataSupertags.div_id + '_wrapper';
    var data = dataSupertags.jsonData;
    document.getElementById(el).innerHTML = '';
    for (i = 0; i < data.length; i++) {
    jQuery.ajax({
      dataType: 'json',
      url: 'APIURL',
      data: {
        count: 5,
        ret_fields: [
          'props.title__AS__title',
          'props.comentCount__AS__cc',
          'fb_shares',
          'props.pubfromdate_local__AS__pubdate',
          'props.href__AS__href',
          "props.media[indexof(x.type='media' for x in props.media)].otheralternate.300x200.href__AS__thumb",
        ].join(','),
        type: 'type1,type2,type3',
        tag_slugs: data[i].topics[0].slug,
        order: 'pubfromdate-'
      },
      success: function(response) {
        var postData = '';
        postData += '<div class="swipe_item">';
        postData += '<header class="swipe_list">';
        postData += '<h1 class="active">' + '<a href="http://test.com/' + data[i].titleurl + '">' + data[i].title + '</a>' + '</h1>';
        postData += '</header>';
        for (f = 0; response.result.length > 0; f++) {
          postData += '<div class="post">';
          postData += '<a href="' + response.result[f].href + '" class="img" style="background-image:url("' + response.result[f].thumb + '")"></a>';
          postData += '<div class="desc">';
          postData += '<h2><a href="#">' + response.result[f].title + ' <span>' + response.result[f].fb_shares + '</span></a></h2>';
          postData += '</div>';
          postData += '</div>';
        }
        postData += '</div>';
        document.getElementById(el).appendChild(postData);
      }
    });
  }
}

Upvotes: 1

lintu
lintu

Reputation: 1102

What you could do is give an id(created dynamically) for each swipe_item and make your ajax call in a separate function, which will be called from your for loop. One of the parameter for the function would be the ID you created, other being data for your ajax call. Once you get back the data in your success function, access the swipe_item using this id (making use of closure) and append the html using append jquery function

Upvotes: 0

Related Questions