What data structure is select2 expecting from the server and how should it be handled? - jquery-select2-4

What data structure is select2 (v4.0.3) expecting from the server and how should it be handled?
The question is asked on the official FAQ here, but there is no answer.
I have tried several variations of data structure, but based on this tutorial and this jsFiddle, have assumed what should be returned from the server is a list/array of objects/dicts, eg:
matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]
I have tried this format with the following Javascript:
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
Firebug results for search on Py:
The search area just displays this:
I am expecting all matches to be showing in the dropdown below the search area.

Solution that worked for me:
Rename json key (it has to be text), so server response is:
[{"text": "Python", "id": 1}]
(after coming across this document).
I also just returned the list itself from the server, rather than making the list a dict value.
Javascript
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});

Related

Search2 - Ajax results with no search

I'm using ajax to pull in data from a php file (which returns json).
I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.
Code:
jQuery('.producttypesajax').select2({
allowClear: true,
placeholder: {
id: '',
text: 'Search by Product Type'
},
ajax: {
url: base + '/appProductTypeSearch.php',
dataType: 'json',
delay: 250,
data: function( params ) {
return {
q: params.term // search term
};
},
processResults: function( data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1
});
jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
});
https://select2.org/data-sources/ajax
I believe there's no native solution for this, but I managed to do it somehow.
Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".
Sample code:
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (jsonObject){
$('#mySelect').select2({ data: jsonObject });
}
});
It worked for me. Hope it helps.

Geo sorting and distance calculation in ElasticSearch not working

UPDATE I've also updated the mapping to include pin as the examples seem to suggest. Also, here's an temporary instance with some data to work with: https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search
I've followed the instructions by ElasticSearch. Using this request:
$.ajax({
url: 'https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search',
method: 'GET',
data: {
sort: [{
_geo_distance: {
"pin.location": [49.8998, -97.1375],
order: "asc",
unit: "km"
}
}]
},
success: function(response) {
console.log(response);
}
});
Does not return with calcuated distance or sorted by distance. I've also tried using "location".
Here's my mapping: https://21991e47cdc7caa8000.qbox.io/profiles/lead/_mapping
Any ideas?
I've managed to get it working, Please see the difference,
I converted data as json before quering, and added some configuration( changed dataType to json, and request type to POST, as we know GET request generally don't have body, only POST request does.
var request = {
sort: [{
_geo_distance: {
"pin.location": [
49.8998, -97.1375],
order: "asc",
unit: "km"
}
}]
};
$.ajax({
url: 'https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search',
type: 'POST',
crossDomain: true,
dataType: 'json',
data: JSON.stringify(request),
success: function (response) {
console.log(JSON.stringify(response));
}
});
Hope this helps.
I've tested, and it should work for you too.
The example given uses pin.location, not location or lead.location.
Additionally, pin.location is an array of length 2, not an object with two fields as you are using it. This seems pretty counter-intuitive to me, as the location field in most other api calls is an object like you are using.
Try this:
$.ajax({
url: "https://myhostedes.com/profiles/lead/_search",
method: "GET",
data: {
"sort": [{
"_geo_distance": {
"pin.location": [49.8998, -97.1375],
"order": "asc",
"unit": "km"
}
}]
},
success: function(response) {
console.log(response);
}
});
Note: I don't have access to an elastisearch instance at the moment, so I haven't been able to run this yet.

select2 remote displaying label instead of id when selecting a value from results

I have the following code in an attempt when selecting a suggestion to display the selected value instead of the id. BUT I still need to pass the id as a value. This works fine when using select2 without remote on a regular select box, but it doesn't seem to work like this on a remote data source using an input.
Here is my results:
Search suggestions (working):
Selection Result (Not working as expected..I expect the search suggestion to be selected):
Here is the code:
$("#specific_input_data").select2(
{
minimumInputLength: 2,
placeholder: <?php echo json_encode(lang('common_search')); ?>,
id: function(suggestion){ return suggestion.value; },
ajax: {
url: <?php echo json_encode($search_suggestion_url); ?>,
dataType: 'json',
data: function(term, page)
{
return {
'term': term
};
},
results: function(data, page) {
return {results: data};
}
},
formatSelection: function(suggestion) {
return suggestion.value;
},
formatResult: function(suggestion) {
return suggestion.label;
}
});
I figured i out. formatSelection needs to be selection.label

JQueryAutoComplete Not showing results

I am trying to bind the text box and the JQuery AutoComplete feature. When I checked the Firebug AJAX Request & Response it returns like the following. But the textbox is not showing any items. Could you please advise me, what I am doing wrong? Thanks.
Here is my coding:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.FullDrugName,
id: item.DrugID
}
}))
}
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
DataType property is representing the type of data that you're expecting back from the server.
you define data type as json but server returns you a xml output. You should change your DataType property to xml
In addition to #fealin's answer, you're going to need to change the way you process the xml response. It doesn't look like you have a d property on the return data, and you also need to look for the correct nodes in the XML structure and pull out their text to build the response array that you return to the widget.
Based on the XML you've provided, it might look something like this:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($(data).find("Drug").map(function (_, el) {
var $el = $(el);
return {
label: $el.find("FullDrugName").text(),
value: $el.find("DrugID").text()
};
}));
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
Here's an example that's just using the XML string (without an AJAX request): http://jsfiddle.net/J5rVP/29/

Infragistics Jquery Tree

I need some help from you in using igTree when LoadOnDemand is set to true.
I have a WCF REST Service which is giving me data to populate in igTree.
Please find the sample code..
$.ajax(
{
type: "GET",
url: "AssessmentProcWCFService.svc/GetAllEntities",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: '{}',
cache: false,
success: OnGetAllEntitiesSuccess,
error: OnGetAllEntitiesFailure
});
==================================================
function OnGetAllEntitiesSuccess(categoryList) {
$("#APTreeView").igTree({
animationDuration: 0,
dataSourceType: 'json',
dataSource: categoryList.d,
initialExpandDepth: false,
loadOnDemand: true,
dataSourceUrl: "AssessmentProcWCFService.svc/GetAllCategories?EntityID=primaryKey:id",
bindings: {
textKey: 'text',
valueKey: 'id',
primaryKey: 'id',
expanded: 'expanded',
childDataProperty: 'children'
}
});
}
=========================================================
Questions:-
How could I send the selected node ID to the Service when any node of the tree is expanding?
The way I am sending in the above example it is not working when I am retrieving it in the service “public List GetAllCategories()” like
“string entityID = HttpContext.Current.Request.QueryString["EntityID"];”
I am getting entity id as null.
How the tree get rendered when any node get expanded if LoadOnDemand is true?
Please help me on this I have spend lot of time in it.
Basically you can encode anything you like in the request made to the service:
Here are the default request parameters explained: http://www.infragistics.com/community/forums/t/65356.aspx
And here is how you can add a request parameter:
function OnGetAllEntitiesSuccess(categoryList) {
$("#APTreeView").igTree({
animationDuration: 0,
dataSourceType: 'json',
dataSource: categoryList.d,
initialExpandDepth: false,
loadOnDemand: true,
dataSourceUrl: "AssessmentProcWCFService.svc/GetAllCategories?EntityID=primaryKey:id",
bindings: {
textKey: 'text',
valueKey: 'id',
primaryKey: 'id',
expanded: 'expanded',
childDataProperty: 'children'
},
nodePopulating: function (event, ui) {
var node = '&SelectedNodeID=' + $("#APTreeView").igTree('selectedNode').element.attr('data-value'),
myNewUrl = 'AssessmentProcWCFService.svc/GetAllCategories?EntityID=primaryKey:id' + node;
$('#myTree').igTree('option', 'dataSourceUrl', myNewUrl);
}
});
}

Resources