Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results.

<script>
  $(document).ready(function() {
    $('#style_full_name').select2({
        placeholder: "Please type in the make and model",
        minimumInputLength: 3,
        ajax: {
          url: "/list_styles",
          dataType: 'json',
          quietMillis: 100,
          data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page, // page number
            };
          },
          results: function (data, page) {
            var more = (page * 10) < data.total; // determining if there are more results available

            // returning the value of more so Select2 can load additional results if needed
            return {results: data.styles, more: more};
          }
        },
        formatResult: styleFormatResult, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // applying css to adjust dropdown height
        escapeMarkup: function (m) { return m; } // not escaping markup since html is displayed in results
    });
    function styleFormatResult(style) {
      var markup = "<table class='style-result'><tr>";
      if (style.dimage_url !== undefined) {
          markup += "<td class='style-image'><img src='" + style.dimage_url + "'/></td>";
      }
      markup += "<td class='style-info'><div class='style-title'>" + style.full_name + "</div>";
      
      markup += "</td></tr></table>"
      return markup;
    }
  });
</script>

When testing the Rotten Tomatoes API from Select2's page and monitoring the network panel in Chrome console, a callback is triggered when scrolling to the bottom of the list. However, in my implementation above, this functionality is not working as expected.

Answer №1

Upon further investigation, I discovered that the issue stemmed from the fact that "total" was missing in my json response. As a result,

var more = (page * 10) < data.total
was returning false. Below is the snippet of code from my Styles controller (RoR) that was necessary to enable infinite scroll functionality:

def list_styles 
  #sunspot solr query
  @styles = Style.search { fulltext params[:q]; paginate :page => params[:page], :per_page => params[:page_limit] }

  #Build Json String
  @styles = "{\"total\":#{@styles.total}, \"styles\":#{@styles.results.to_json(:only=>[:id, :full_name], :methods => [:dimage_url, :dimage_url_medium])}}"

  #Render Json Response
  respond_to do |format|
    format.json {render :json => @styles }
  end
end

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

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Is there a way to give a ReactJS button a pressed appearance when a key is pressed?

I recently developed a Drum Machine using ReactJS, but I'm facing an issue with making the buttons look like they've been clicked when I press the corresponding key. I came across a similar query on this site, however, I'm having trouble imp ...

Exploring the contrast: resolve() versus fulfill() in q.js

I'm finding it difficult to understand the distinction between calling a resolver's resolve() as opposed to fulfill(). Both functions and terms "resolve a promise" and "fulfill a promise" are frequently used interchangeably. Can you provide guid ...

Unable to remove data once it exceeds 10 entries while using AJAX, jQuery, and JavaScript/PHP

I am having an issue where I can insert data into the first 10 rows and delete any of them successfully. However, when I try to insert data starting from the 11th row, I am unable to delete any rows past the 10th. UPDATE: The deletion function does not wo ...

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

Mobile device users experiencing issues with jQuery scroll up and down functionality

Currently, I am utilizing jQuery to identify when a user is scrolling the mouse wheel up or down. Below is my code: $(window).bind('mousewheel DOMMouseScroll', function(event){ if (event.originalEvent.wheelDelta > 0 || event.originalEvent ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

How to set cells to plain text in google sheets

I've been grappling with a formatting issue that I'm hoping someone can assist me with. In my script, there's a point where I need to combine the date value (e.g., 11/20/2020) from one column with the time (3:00 PM) from another column. This ...

Implementing numerous dropdown input features within a single webpage

I am facing an issue while trying to pass a URL with parameters through a dropdown select input by calling a function using the onchange event. The problem arises when there are multiple dropdowns on the same page, each triggering the same function. Even ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

On the server side, the received Req.body appears as an empty object: { }

import { Injectable } from '@angular/core'; import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; impo ...

Choose an item from a list that does not have a particular class

Here is a list of items: <ul id='myList'> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class='item-selected'>Item 4</li> <li>Item 5</li> & ...

Send information via Ajax without relying on jQuery functions

Looking for a way to securely send a private access_token via http POST using Ajax code. Any suggestions on achieving this with the code provided below? function getstatus(url, placeid, access_token) { if(window.XMLHttpRequest) ...

How to convert deeply nested object structures containing arrays in JavaScript

Despite the less-than-desirable name of this inquiry, the question is fairly straightforward. I have a particular object: let test = { date1: [ { time: 1, value: 5, }, { time: 2, value: 6, }, ], date2: [ { ...

Is there a conflict between bootstrap.min.JS and chart.min.js?

I have been working on developing an admin page for customer support and I recently added a visually appealing chart to display some data on the home screen. The chart integration was successful, but when I introduced tab panes to the page and refreshed ...

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...