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!