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

Refreshing page using jQuery following an AJAX request

My script is functioning properly, however the use of location.reload(); does not seem to be effective. I am aiming to refresh the page after deselecting the last checkbox. $(".catcf, .coursetype, .yearcf, .manthcf, .venucf").on('click' ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

Adjust the quantity of divs shown depending on the value entered in a text input field

It seems like I am on the right track, but there is something simple that I am missing. I'm currently utilizing the jQuery knob plugin to update the input field. $('document').ready(function() { $(".knob").knob({ c ...

Guide on how to combine the strings retrieved from an API

I'm having trouble concatenating multiple sentences together and highlighting specific words in each sentence. Although I can successfully highlight one sentence using the code below, I haven't been able to concatenate more than one sentence: th ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

Is there a way to change the color of a specific tab without affecting the content within it

I am attempting to change the color of an individual tab using jQuery. However, when I set the background attribute in CSS, it colors the entire background instead. What specific property should I be setting to only change the color of the tab itself? ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

Updating Jqplot display upon ajax call completion

Currently, I have a Jqplot set up using the AJAX JSON Data Renderer and it's functioning properly. There is a button on the page where users can input new values (updated through ajax) which are then stored in the same DB as the json data source. Whe ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

Avoid positioning issues when dropping a DIV onto the Canvas

Utilizing the JavaScript code below allows me to drag a DIV onto a canvas. I am currently loading a multi-page PDF, which consists of image files, in a pop-up window and positioning canvas layers over them. In these canvas layers, shapes are then loaded at ...

Implement responsive data tables by setting a specific class for hiding columns

Having trouble assigning a specific class name to individual columns in datatables? It seems that when columns are hidden using the responsive extension, the desired class is not applied. Looking for a solution or workaround. Check out this example from D ...

Encountering difficulty in reading a session variable when accessing it through Ajax, however, the variable is successfully retrievable when called from the controller in ASP.Net

I have implemented a method within the controller to retrieve the value of a session variable. However, when I attempt to call this method from Ajax jQuery, I am unable to obtain the value. Interestingly, if I try to read the session value from another met ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

there is no httpPost run method available

I'm experiencing an issue with my MVC application where the browser is unable to send POST data to the controller method. When testing with the "GET" parameter, the parameter is successfully passed. However, when using "POST", nothing happens and it&a ...

Is it possible to utilize the node package ssh2 within a web browser environment?

I am working on a project for school where I am creating an SFTP client directly in my browser. I have successfully implemented the node package ssh2 and it works perfectly when running the code in the terminal. I can connect to the server, read directorie ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...