Infinite scroll feature in Select2 fails to load next page when fetching remote data

I am currently working with Select2 4.0.1. I have utilized ajax to dynamically populate search results based on user input. However, I am facing an issue where the initial search displays results from the first page only and subsequent pages do not load. Additionally, a request is triggered for the second page upon scrolling. It seems like I may be overlooking something in my implementation.

$multiselect = $(element).select2({
    closeOnSelect: false,
    multiple: true,
    placeholder: 'Assign a new tag',
    tags: true,
    tokenSeparators: [","],
    ajax: {
      url: '/search_url',
      dataType: 'json',
      type: 'GET',
      delay: 250,
      data: function(params) {
        return {
          search: params.term,
          page: params.page
        };
      },
      processResults: function(data, params) {
        var more, new_data;
        params.page = params.page || 1;
        more = {
          more: (params.page * 20) < data.total_count
        };
        new_data = [];
        data.items.forEach(function(i, item) {
          new_data.push({
            id: i.name,
            text: i.name
          });
        });
        return {
          pagination: more,
          results: new_data
        };
      },
      cache: true
    }
  })

Any assistance on resolving this issue would be greatly appreciated. Thank you :)

Answer №1

Last week, I successfully implemented this code with a different transport feature on my end. Despite the distinction in transport methods, it did not affect the overall functionality. My initial struggle was similar to yours - the paging did not work properly while scrolling. Upon closer inspection, I realized that the issue stemmed from an incorrect format of {'pagination':{'more':true}} within my processResults function. Perhaps adjusting the page count alignment between the data and processResults functions may resolve your problem.

When you reach the bottom of the list, do you observe the "Loading more results..." message? Have you considered setting the more value to true manually for debugging purposes?

        this.$(".select2").select2({
            'ajax': {
                'transport': function (params, success, failure) {
                    var page = (params.data && params.data.page) || 1;
                    app.do('entity:list:search',{'types':['locations'],'branch':branch,'limit':100,'page':page,'term':params.data.term})
                    .done(function(locations) {
                        success({'results':locations,'more':(locations.length>=100)});
                    });
                }
              , 'delay': 250
              , 'data':function (params) {
                    var query = {
                        'term': params.term
                      , 'page': params.page || 1
                    };

                    return query;
                }
              , 'processResults': function (data) {
                    return {
                        'results': data.results
                      , 'pagination': {
                            'more': data.more
                        }
                    };
                }
            }
          , 'templateResult': that.formatResult
          , 'templateSelection': that.formatSelection
          , 'escapeMarkup': function(m) { return m; }
        });

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

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

Guide on incorporating AJAX in PHP by utilizing functions

I'm looking to create a web app utilizing json, ajax, and php. Specifically, I need a php page with various functions that can be accessed through an ajax method. For example: phppage.php addmydetails() { // code implementation here } Ajax Page ...

Arrangement of div elements tailored to fit the size of the viewport

I am working on creating a grid of divs that will cover the entire viewport. To start, I want to have a grid that is 7 divs wide and 10 divs high. Below is the code snippet I've written so far to set the size of the div elements: function adjustHeig ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

Suggestions for Implementing a Smooth Login Experience in React Native

As a newcomer to the world of react-native, I am facing a challenge in creating a login feature that interacts with our backend APIs on AWS. The goal is to navigate to the home screen upon receiving a token from the API, while displaying an error message i ...

Experiencing difficulties while iterating through a basic JSON array

When I iterate through the ajax array, the index and value are being displayed incorrectly. $.ajax({ url: '/ajax/deal_start_times/' + $pid, success: function(data){ var tmp = ""; $.each(data, function(index, value) { ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

Can Jquery be utilized to signal a language change?

I'm working on my portfolio website that will be available in two languages, Thai and English. I have successfully implemented language buttons for changing between the two languages. However, I am facing an issue with the language selection when nav ...

Align the image so that it is perfectly positioned along the lower edge of the window

I have been experimenting with parallax scrolling and resizing images using JavaScript. However, I am struggling to align my homepage perfectly with the edge of the window. The code I have doesn't line up with the bottom edge of the webpage. If I us ...

How can I stop and hover over time in AngularJs Interval?

Within my UI, I have a time element that is continuously updated using AngularJS Interval. Even the milliseconds are constantly running. Is it possible to implement a feature where the time pauses when hovering over it? Any assistance would be greatly appr ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

In a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

One option is to use several controllers, while another is to have

Query I have a design dilemma regarding whether to use a single "Master Controller" script that interacts with PHP classes for all business logic, or to create multiple smaller controllers focusing on specific tasks. Scenario For instance, if I need ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

What is the best way to assign a data attribute value based on an element's index using jQuery?

I am dealing with multiple sibling elements that are added dynamically or manually using JS. Each element has a data attribute called "data-sec_number" with a number value that increments by one for each subsequent element down the page. Currently, I am ma ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Looking to transfer zip files from a React user interface to a Node.js server backend, where I can then save the folder to a specific directory on my system

Frontend I am currently working on a feature that involves uploading a zipped folder containing CSV files from the React UI input field. import React, { useState } from "react"; import axios from "axios"; function App() { const [uplo ...

Tips for updating a specific section of a Django webpage using AJAX

Currently, I am in the process of launching a website using Django. One crucial application on this site is the 'forum' which facilitates discussions among users. The discussion forum can be accessed through the URL 'XXX.com/forum/roomY&apo ...

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...