0

I know, this was asked several times on SO (eg here), but nothing worked for me.

I have a JSON Import via ajax. This imports data for a slick slider. So the slick slider should be initialized after the ajax import finished.

My Code:

  // Import Ticker
  $.ajax({
      url: '/de/data/data.json',
      type: 'GET',
      datatype: 'json'
  }).success(function (data) {
      for (var i = 0; i < data.length; i++) {
          var obj = data[i];
          $('section.ticker .slider').append(`
            <div class="slide">1</div>
            <div class="slide">2</div>
            <div class="slide">3</div>
          `)};

      $(document).on('ready', function() {
        $('.slider').slick({
            infinite: true,
            slidesToShow: 3,
            slidesToScroll: 3
        });
      });

      // Error handler
      }).error(function (err) {
          console.log(err);
      })

I also tried:

  }).success(function (data) {
      for (var i = 0; i < data.length; i++) {
          var obj = data[i];
          $('section.ticker .slider').append(`
            <div class="slide">1</div>
            ...
          `)};
      }.complete: function (data) {
        $('.slider').slick({
          infinite: ...
        });
      }).error(function (err) {
          console.log(err);
      })

Or this:

$( document ).ajaxStop(function() {
  $('.slider').slick({
     infinite: ...
  });
});
Maximilian Neuse
  • 153
  • 1
  • 5
  • 15
  • Not sure, but I would start with having `$(document).on('ready' ...` and then put ajax call inside it. Then, after for loop is finished I would place $('.slider').slick( ... ) – Hero Qu Oct 02 '19 at 12:52
  • Why did you choose to use `$(document).on('ready', ...)` inside the `success` of the ajax call in your first example? Is there a reason not to have the `.slick()` call run immediately after the loop appends the `.slide` elements? – daddygames Oct 02 '19 at 13:12

1 Answers1

1

Please remove slick initialisation from $(document).on('ready',function(){});

Your code will look like

$.ajax({
      url: '/de/data/data.json',
      type: 'GET',
      datatype: 'json'
  }).success(function (data) {
      for (var i = 0; i < data.length; i++) {
          var obj = data[i];
          $('section.ticker .slider').append(`
            <div class="slide">1</div>
            <div class="slide">2</div>
            <div class="slide">3</div>
          `)};

        $('.slider').slick({
            infinite: true,
            slidesToShow: 3,
            slidesToScroll: 3
        });

      // Error handler
      }).error(function (err) {
          console.log(err);
  })
NITIN PATEL
  • 460
  • 5
  • 12