2

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?

10
  • try ajax property async = false Commented Mar 17, 2017 at 9:09
  • @AmeyaDeshpande Hey, thanks for the answer but it did not seem to help. What it does now, it loops one time through the first tag, returns me the two posts, and then breaks, for the second swipe_item im getting an undefined error in response. Commented Mar 17, 2017 at 9:15
  • 1
    @AmeyaDeshpande never ever do that. Commented Mar 17, 2017 at 9:20
  • If you could create a dummy superTags object along with the question cz its undefined Commented Mar 17, 2017 at 9:24
  • @RoryMcCrossan yes its a bad practice to hang UI but I guess this will help if there is no any other option Commented Mar 17, 2017 at 9:25

2 Answers 2

1

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);
      }
    });
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Greetings @Joe , Your answer was very helpful for getting me on a track! Altrough, I still run into some problems. Now I'm getting an undefined error in ajax response while doing for loop. I logged console with response, it returns what it should. Heres few screenshots that I took : imgur.com/ySoXdXE imgur.com/LV5PaLW
Sorry I didn't validate the code you posted, I just split it up into the functions. Your for loop for f looks a bit suspect. Perhaps it should be for(var f = 0; f < response.result.length; f++)
Yes, I figured it out, it was 0 < response.result.length instead of f < response.result.length. Problem sorta solved, thank You very much! I upvoted but since I'm new here I don't know if it counts. I have one last question left to ask - how do I pass a "for" loop variable into the success response? I need to access data[i].title inside success. Any clues?
Nevermind - I solved this last problem I had by wraping my ajax request inside a (function(i){...})(i); and puting it inside for loop. Thank You everyone for Your answers and help, this community is awesome!
0

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

1 Comment

Thanks, Lintu, seems like a good idea, I will try it out and report!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.