The Select2 widget passes parameter term spaces to the ajax request as a plus sign "+" instead of %20

I have been working on an application that connects to SAP's service layer and retrieves data using REST APIs. I am using the popular widget select2, but I have encountered a problem. The API query that needs to be made contains a space character around the "or" operator:

"(startswith(CardCode,'"+params.term+"') or startswith(CardName,'"+params.term+"'))

The spaces surrounding the "or" operator are causing issues in my code.

Here is the code snippet:

$('#buscarCliente').select2({
        placeholder: "Enter client code or description",
        allowClear: true,
        language: "es",

        ajax: {
            url: SLServer+"BusinessPartners",
            crossDomain: true,
            xhrFields: {
                        withCredentials: true
            },
            dataType: 'json',
            type: 'GET',
            delay: 550,
            params: {
                contentType: 'application/raw; charset=utf-8'
            },
            data: function (params) {
              return {

                $filter: "(startswith(CardCode,'"+params.term+"') or startswith(CardName,'"+params.term+"'))", // Search query
                $orderby : "cardName",
                page: params.page
              };
            },

            processResults: function (data, params) {
            params.page = params.page || 1;

           return {
              results: $.map(data.value, function(item) {
                    return { id: item.CardCode, text: "<b>"+item.CardCode+"</b> "+item.CardName }; // Format the array for select
                }),
              pagination: {
                    more: (params.page * 30) < data.total_count
              }
            };
          },
          cache: true
        },
        escapeMarkup: function (markup) { return markup; },
        minimumInputLength: 1
      });

The issue I am facing is that select2 encodes the query in a way that replaces spaces with plus symbols instead of "%20", causing the REST API service to flag it as illegal characters and returning no results.

Here is how the encoded query looks:

https://service.net:50000/b1s/v1/BusinessPartners?%24filter=(startswith(CardCode%2C%27CLIEN%27)+or+startswith(CardName%2C%27CLIEN%27))&%24orderby=cardName

As you can see, the spaces are being replaced by plus symbols. I have tried using the JavaScript functions encodeUri() and encodeURIComponent(), but it seems the encoding is done internally. I have also tried manually replacing spaces with "%20", but the result is even worse (%2520)...

Can anyone provide a solution to change this encoding so that spaces are replaced with "%20" instead of "+"?

Thank you for your help!

Answer №1

It was a lightbulb moment for me.

While delving into the documentation, a crucial revelation dawned on me: I can extract the ajax "url" property from a javascript function by passing the search term as a parameter. With this information, I crafted the url by combining the query string and utilizing the encodeURI javascript function - and voila, it worked like a charm! :-D

ajax: {
            ....

            url: function (params) {
                return SLServer+"BusinessPartners"+encodeURI("?$top=15&$filter=((startswith(CardName,'" + params.term.toUpperCase() + "') or startswith(CardCode,'" + params.term.toUpperCase() + "') or startswith(CardName,'" + params.term + "') or startswith(CardCode,'" + params.term + "')) and CardType eq 'C')&$expand=PaymentTermsType";);
            },

            ....

The white spaces are cleverly transformed into %20 within this function, keeping the api content and yielding the desired results...

May this insight be of assistance to others. Warm regards from Venezuela ;-)

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

"Utilizing AngulaJS to apply a class to the parent element when a radio button is

I'm wondering how I can assign a class to the parent div of each radio button in a group? You can find the code below and view the corresponding JSFiddle here. Here is the HTML: <div class="bd"> <input type="radio" ng-model="value" val ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...

increasing the size of an array in react javascript

componentWillMount(){ this.adjustOrder(); } componentDidMount(){} adjustOrder(){ var reorderedArray = []; this.state.reservation1.length = 9; for (var i = 0; i < this.state.reservation1.length; i++) { if(this.state.reservation1[i]){ r ...

What is the best way to retrieve an item using a composite key?

const dynamoDB = new AWS.DynamoDB.DocumentClient(); var parameters: any = {}; parameters.TableName = 'StockDailyCandles'; var primarykey = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // sa ...

Dealing with a surprise JSON error in Express.js using Javascript

Dealing with Unexpected JSON in my express js application using try and catch. I attempted to achieve this as follows: try{ let body = JSON.parse(req.body); }catch(e){ res.json({ error:e }) } However, the Unexpected JSON error is not caught in ...

AngularJS and Karma: Revoking ng-dirty status using setPristine

I'm currently facing an issue in one of my unit tests where I am testing the removal of ng-dirty when using setPristine on an input element. Even after calling setPristine, the ng-dirty is not being removed. My suspicion is that I may be incorrectly ...

Unable to process the post request

I've encountered an issue while attempting to redirect using the res.redirect() function. When I submit the form, it should insert the data into the database and then redirect me to the home root. However, instead of successfully redirecting, I'm ...

Angular's '@angular/core/core' module does not have the exported member 'ɵɵFactoryDeclaration'

My Angular application was successfully compiled after running npm install. However, upon executing npm start, I encountered the following error: ERROR in node_modules/ng-apexcharts/lib/chart/chart.component.d.ts:57:21 - error TS2694: Namespace '&quo ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

"What is the best way to create a hyperlink in Google Apps Script using HTMLService? (encountering an error with the connection to accounts.google.com

Trying to utilize the Apps Script method setContent() in Google Apps Script to insert a link into a basic index.html file. var newDocLink = "https://docs.google.com/document/d/1loBt7T7-4qd0ORBXiTFeDQxuG..."; // newDocLink variable is set with a Googl ...

AJAX delivers numerous results

My goal is to retrieve multiple values simultaneously, but I am encountering a problem where only one value is being returned successfully. This is my approach : <script type="text/javascript"> $(document).ready(function () { ...

What could be causing my express router.get endpoints with multiple paths to only render text?

Currently, I am in the process of configuring a password reset flow using Pug (formerly Jade) and Express. Oddly enough, GET requests that contain URLs with multiple appended paths are causing my Pug view files to render with only text. The images and sty ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

Utilizing every function across various offspring

Is it possible to use the each function on multiple children at once? The code below shows my attempt to use the each function on both child elements in a single line. $('.right .submission:not(:first)').each(function(){ stud ...

Using jQuery to follow a div while scrolling that halts at a designated top or bottom boundary

I've been working on this jsfiddle: https://jsfiddle.net/3ncyxnzt/ Currently, the red box stops at a specified margin from the top of the page but I want it to also stop before reaching the bottom, so that it doesn't go under or over the footer. ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Creating a MySQL table that includes long string data types

Recently, I was working on creating an online forum and encountered a problem with the writing function. The form consists of a title and content section, which usually functions properly. However, when I enter a slightly longer text in the content field, ...

Implementing batch processing and scheduling API requests in node.js using async functions

I am currently working on analyzing a social network graph, specifically focusing on creating a "six degrees of separation" tree based on adjacency lists obtained from an API. The challenge lies in the fact that there is a large number of individuals in t ...