Run a function once the ajax request has been completed

Despite seeing similar queries on SO multiple times (such as here), I couldn't find a solution that worked for me.

I am using ajax to import JSON data for a slick slider. The slick slider needs to be initialized after the completion of the ajax import process.

Here's 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 attempted the following alternatives:

  }).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: ...
  });
});

Answer №1

Kindly refrain from using slick initialization in

$(document).on('ready',function(){});

Your revised code should resemble the following:

$.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
        });

      // Handling Errors
      }).error(function (err) {
          console.log(err);
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making a jquery ajax call to send a request to a specific domain

Is it possible to send a request using AJAX? Can we use the domain name along with the file in URL property of AJAX? If not, what should be used instead? $.ajax({ url:'http://www.domain.com/myfile.php', }) Thank you. https://i.stack.imgur. ...

What is the process for setting the version in a serverless project?

Recently I downgraded the serverless to version 1.38.0 using the command npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047761767261766861777744352a373c2a34">[email protected]</a>. This triggered in ...

What could be the reason for the lack of styling on the select element when using PaperProps in the MenuProps of my Select component?

I've been struggling to remove the white padding in this select box for a while now. I've tried countless variations and places to tweak the CSS with no success. Any suggestions on how to make it disappear? The project is using MUI 5, and I even ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

Having trouble uploading images using ReactJS on the web platform

I am currently in the process of developing a portfolio website using react js, but I'm experiencing an issue where the image I intended to display is not showing up on the live site. Despite thoroughly checking my code, I can't seem to identify ...

What steps should I follow to transform SRM into L*a*b* values using the E-308 algorithm?

I'm grappling with the application of ASTM E-308 to SRM measurements in beer. The project I'm working on necessitates a reliable conversion from SRM to RGB (or sRGB) through the Lab* route. It's clear that each site I visit for beer recipe c ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

Ways to trigger a 406 Error (Not Acceptable) using jQuery

Currently, I am implementing error handling in my.js file. This involves making cross-domain calls to another server and utilizing Mustache.js for dynamic HTML templates. $.getJSON(url, function(data, textStatus, xhr) { $.each(data, function(i, data) { ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

Selenium Python option other than using send_keys()

I was looking to enhance the efficiency of this Python code and found a faster alternative: driver.get(myUrl) message = driver.find_element_by_id('message') send = driver.find_element_by_id('submit') for _ in range(myRange): messa ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Perform activities within a component responsible for displaying a flatlist

I have a component called Post that I'm using to display posts within a FlatList. Currently, the Post component only shows text and images in the Flatlist. However, within the Post component, there are buttons that should have functionality such as de ...

Having trouble making an Ajax request using the Yahoo API?

Any thoughts on why this code is failing? $(document).ready(function () { doAjax("http://somedomain.com/page.aspx"); }); function doAjax(url) { if (url.match('^http')) { $.getJSON("http://query.yahooapis.com/v1/public/yql?" + ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Conceal the element if the offspring is devoid of content

I want to implement a feature where a div is hidden when its child element is empty. To achieve this, I aim to assign the class .no-content to the div if it contains no elements. Below is my existing code with spaces: <div class="ee-posts-list&quo ...

Using Selectpicker with Jquery .on('change') results in the change event being triggered twice in a row

While utilizing bootstrap-select selectpicker for <select> lists, I am encountering an issue where the on change event is being triggered twice. Here is an example of my select list: <select class="form-control selectpicker label-picker" ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Tips for generating nested elements in JSON and Java, alongside accessing the subitem values in JavaScript

By implementing this code, I was able to create the following structure int n=3; String json []= new String [n]; try { JSONArray js = new JSONArray(); ArrayList<String> ciudades; ciudades = ...

Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript. To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bu ...