Select2 - Issue with AJAX causing search results to not display in dropdown

Currently using Select2 version 4.0.1. Implemented ajax to display results based on user input, but facing an issue where Select2 does not list any results despite receiving the proper response from ajax.

Additionally, the input box loses focus after the ajax response.

This is how Select2 was initialized:

$('#select_tag_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) {
            console.log(data)
            return {results: $.map(data, function(item) {
                    return {id: item.id, text: item.name}
                })
            };
        },
        cache: true
    }
});

The expected JSON object is retrieved in the Javascript Console.

[Object, Object, Object]
0: Object
id: 239
name: "Tag1"
__proto__: Object
1: Object
id: 255
name: "Tag2"
__proto__: Object
2: Object
id: 256
name: "Tag3"
__proto__: Object
length: 3
__proto__: Array[0]

Any assistance would be highly appreciated. Thank you :)

Update -

Upon debugging, noticed that the result dropdown appears initially but gets removed when

globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
line is executed in jquery.js.

if ( fireGlobals ) {
  globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
  // Handle the global AJAX counter
  if ( !( --jQuery.active ) ) {
    jQuery.event.trigger( "ajaxStop" );
  }
}

Is there a way to prevent the result dropdown from closing upon the above trigger?

===============================================================

Update

Solved the issue by realizing I had initialized Select2 on ajax success, causing the result dropdown to hide.

Answer №1

I made some adjustments to your code for improved functionality

$('#select_tag_element').select2({
  closeOnSelect: false,
  multiple: true,
  placeholder: 'Choose a 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) {
      var newData = [];
                    data.forEach(function (i,item) {
                        newData.push({
                            id: i.id  //id from data
                            , text: i.name  //display name
                        });
                    });

            return {
            results: newData
          };
    },
    cache: true
  },
   formatResult: function(data) {
        return data.name;
    },
    formatSelection: function(data) {
        return data.id;
    },
    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

The error message in monodb.js at line 2: "require is not defined" indicates an issue with the 'require' statement not being

const { MongoClient } = require("mongodb") const url='mongodb://localhost:27017' const client=new MongoClient(url); async function fetchData(){ let result=await client.connect(); let db=result.db("first& ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Dealing with the information received from a PHP response during an AJAX request using JavaScript

Here is my PHP script <?php //establishing connection to the server //selecting the database $temporaryArray = array(); $counter = 0; $result = mysql_query("some query"); while($row = mysql_fetch_assoc($result)) { $temporaryArray["$counter"]= $row[" ...

How to retrieve the content of <p> elements by their id or class in PHP

I am currently utilizing a Script that enables the display of URL content within the meta tag "description". This script utilizes PHP in the following manner: $tags = get_meta_tags($url); Subsequently, it is called like so: <label class="desc"> ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

The Material-UI DataGrid feature allows for the display of column sums, with the sum dynamically updating based on applied filters

I am struggling with calculating the sum of values in the Total Amount column of my Material-UI DataGrid. How can I achieve this and ensure that the sum is also updated when a filter is triggered? Any guidance on how to sum the entire Total Amount column ...

Error: StalePageException occurred in the wicket framework

I am currently using Wicket version 6.20. Within a Wicket page, I have implemented an AbstractDefaultAjaxBehavior to capture mouse clicks and their x,y coordinates: class CallFromJavaScript extends AbstractDefaultAjaxBehavior { private static final l ...

Find the vertices located on the "upper surfaces" of the ring using Three.js

I'm currently immersed in a project centered around creating different types of "rings" using Three.js. Each ring is formed through an algorithm I designed myself, which involves defining 4 sections placed at π, π/2, 3π/2, and 2π, then utilizing q ...

Tips for resolving the issue of missing metadata for open graph and Twitter cards in a Next.js project

Having trouble with error messages while running the build version in Next.js. I've added meta tags to the layout, but the issue persists. As a newcomer to Next.js, I'm looking for guidance on how to fix this problem. Any help or advice on troubl ...

Checking forms for standard regulations with jQuery

Within my project, I have implemented multiple forms, where each form shares common fields like email, but also contains its own unique fields such as uniqueFieldA for Form A and uniqueFieldB for Form B. The challenge at hand is to develop a set of valida ...

Is it time to use the JavaScript preload() function?

When I initially select a radio button, I experience a brief freezing effect. However, upon selecting them a second time, everything operates smoothly. I suspect this is due to the radio buttons being stored in the browser cache. Is there a way to preloa ...

Encountering an error stating 'ReadableStream is not defined' while attempting to log in using Discord on the NextAuth application

While attempting to set up a Discord sign-in page to test NextAuth on my website, I encountered the error ReferenceError: ReadableStream is not defined. After examining the stack trace, it seems to be related to how my packages are configured, but I' ...

The execution of consecutive Ajax requests encounters issues in the Google Chrome and Safari browsers

I am facing an issue where I encounter a problem displaying a sequence of dialogue or AJAX results that depend on each other. For instance, when a user clicks to send a message, it triggers an ajax call, which opens a dialogue box. The user fills out the f ...

Guide on how to show an icon in Meteor when a link is clicked

Is there a way to display a viewed icon upon clicking a link in Meteor? On my list of jobs page, when a user clicks on a job, they are taken to the description page. I would like to add an icon to the post indicating that the user has viewed it. ...

Changing the color of a menu item in Bootstrap when a modal window is closed: A guide

I am implementing Twitter Bootstrap and attempting to launch a modal popup by clicking on a menu item. Below is the code snippet: <div class="navbar navbar-fixed-bottom"> <div class="navbar-inner"> <ul class="nav pull-right"> ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

AngularJs JSON endpoint modifier

I've been working on a simple weather app in Angular for practice, but I've hit a roadblock. Here's the Angular JSON feed I'm using: app.factory('forecast', ['$http', function($http) { return $http.get('http: ...

Javascript and JSON: Making Updates to Files

Working on a program, I am faced with an issue while sending a literal variable to local storage using JSON.stringify. My goal is to continuously update the local storage and append to the existing data stored. The problem arises during the parsing of the ...