Issues arise when the Slick functionality fails to load following an ajax request

I've come across a situation similar to the one on this post. I'm having trouble getting my slick carousel to work after a successful ajax call. Despite trying all the solutions provided, it's still not functioning as expected.

The code for initializing slick:

$('.reviews-page-carousel').slick({
    arrows: false,
    slidesToShow: 1,
    variableWidth: true,
    centerPadding: '10px'
});

Ajax call section:

$.ajax({
    type: "GET",
    url: review_url + "?page=" + page,
    success: function(result) {
        $('.reviews-page-carousel').slick('unslick').slick('reinit');
    }
})

An alternative approach I tried:

$.ajax({
    type: "GET",
    url: review_url + "?page=" + page,
    success: function(result) {
        $('.reviews-page-carousel').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
        $('.reviews-page-carousel').slick(getSliderSettings()); /* Initialize the slick again */
    }
});

Unfortunately, both methods resulted in the following error:

Uncaught TypeError: Cannot read property 'unslick' of undefined

Answer №1

Make sure to destroy the slick section before assigning new data:

function destroyCarousel() {
    if ($('.reviews-page-carousel').hasClass('slick-initialized')) {
        $('.reviews-page-carousel').slick('unslick');
    }
}


function applySlider() {
     $('.reviews-page-carousel').slick({
             arrows: false,
             slidesToShow: 1,
              variableWidth: true,
              centerPadding: '10px'
     });
}

After assigning new data, remember to call the slick function again.

$.ajax({
    type: "GET",
    url: review_url + "?page=" + page,
    success: function(result) {
        destroyCarousel(); // remove slick slider first
        $('.reviews-page-carousel').html(''); // empty the html
        $('.reviews-page-carousel').html(result); // integrate new data
        applySlider(); // reapply slick slider
    }
})

Please give this solution a try and feel free to reach out if you need further assistance.

Thank you

Answer №2

Make sure to activate the slick slider only after an AJAX call with a setTimeout function.

var settings = {
    arrows: false,
    slidesToShow: 1,
    variableWidth: true,
    centerPadding: '10px'
}

$.ajax({
    type: "GET",
    url: review_url+"?page="+page,
    success: function(response){
        setTimeout(function () {
            $(".reviews-page-carousel").slick(settings)
        }, 500);
    }
})

Important note: avoid initializing the slick slider immediately, wait for the AJAX response and then activate it using a timeout.

Answer №3

Solution

var settings = {
    showArrows: false,
    numSlidesToShow: 1,
    adaptiveWidth: true,
    paddingCenter: '10px'
}

Ajax

$.ajax({
        method: "GET",
        url: review_url+"?page="+pageNum,
        success: function(response){

            setTimeout(function () {
                $(".reviews-page-carousel").not('.slick-initialized').slick(settings)
            }, 500);

Answer №4

this method worked perfectly for me

fetch('URL')
.then(res=> res.json())
.then(data=> {
// insert the data into slider
$('.myslider').append('data')
// finally,
$('#slick-slider').slick('refresh'); //Tested on slick 1.8.1

}

Find more information here

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

Updating a user's password in Node.js using an AJAX request from a bootstrap form

I've been encountering a POST /user?userid=something 404 error while attempting to enable users to update their password without reloading the page. Can someone point out what I might have done incorrectly? Thank you. Utilizing Bootstrap modal ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...

Images are not loading in NextJs image component on a Digital Ocean deployed application

I recently encountered an issue with my NextJs project. While using the NextJs Image Component for images, everything worked perfectly fine when running locally. However, after deploying the project on Digital Ocean, all the images served through the Next- ...

Eliminate redundant data by utilizing oData to streamline information

I'm trying to clean up my data and eliminate duplicates using oDATA. Currently, I am using !summary=Name in my query, however it's not creating groups and providing the results as expected. Below is my query: http://localhost:12585/OData.svc/Med ...

Adjust the CSS property of a div to have a fixed position when scrolling

I attempted to implement a fixed div on scroll in Vue.js using the following code: ... async created() { window.addEventListener('scroll', this.calendarScroll); } methods: { calendarScroll() { console.log('Scroll'); cons ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

Using CakePHP to create an Ajax form that automatically submits when a user clicks away

I am a beginner in CakePHP and Ajax, and I am facing some challenges while trying to implement Ajax validations in a specific scenario. As mentioned in the title, I am submitting the form on a jQuery blur() event. Each time an ajax request is made, upon s ...

Prevent legend strike-through on click in Vue Chart.js

Recently, I made the transition from vue 2 to vue 3 on my website and part of that process involved updating vue-chartjs and chartjs too. However, after modifying the legend text of my pie chart using the generateLabels option (as seen below), the striket ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local anim ...

Error: Uncaught TypeError when using a for loop in Vue and GraphQL

I encountered a TypeError while attempting to iterate through a GraphQL query in my Vue project. The script snippet in question is as follows: <script> import { useQuery } from "@vue/apollo-composable"; import gql from "graphql-tag&qu ...

Identify and troubleshoot scripts that are included in the response returned by Chrome

I am facing an issue where I have a webpage that loads HTML sections through an AJAX call. The response includes both HTML and JavaScript files. Currently, I am trying to figure out how to set a debug point on the JavaScript file. In Internet Explorer, I ...

JSON.Parse allows for graceful degradation of data when handling JSON objects in JavaScript

What should be done if a browser does not support JSON.parse? Would it be appropriate to include json.js and use parseJSON instead? Here's an example of how the code could look: var output; if (JSON.parse) output = JSON.parse(data); else ou ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

Leverage JSON data to generate individual elements, rows, and columns for every object within the array

Just starting out with JavaScript and struggling a bit. We need to fetch data from this URL: and then manipulate the data to create new rows (tr) and columns (td) for each game without altering the HTML file. The desired outcome should resemble this: I&a ...

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

Interacting with RESTful web services using jQuery

I'm working on a web service that provides data in JSON format through a specific URL. My current challenge involves figuring out how to store this data in a variable using jQuery. Here's what I've attempted so far: $.ajax( { type:'G ...