how to use select2 jquery plugin with Ajax? - javascript

I'm using Laravel5 with Jquery plugin Select2 in this cause I used Ajax to retrieve data from DB and display when using type any word.
Here is my Ajax.
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
Here is my HTML
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
But it is not work for me.

Related

Select2 JQuery's AJAX Method from example is not working

I want to create a search input field using select2.js 4.0.5. I looked at the select2 example and basically, want to learn by recreating them without using the template result (only return text).
However, I cannot make it work. This is the closest I can get: myJSFiddle.
$(document).ready(function() {
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
}
});
});
Even copying directly everything from the example does not work: exampleJSFiddle.
I am still new to JS and Ajax. I'm sure that I'm missing something. Could someone please explain what am I missing?
I finally get it running. Although I don't know how to fix the size of the search box: (Working JSFiddle)
HTML
<select class="js-data-example-ajax"></select>
JS
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
contentType: 'application/json',
dataType: 'json',
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
return {
results: data.items
};
},
cache: false
},
templateResult: formatResult
});
function formatResult(result) {
return result.full_name;
};

How to provide a datasource for Select2 with October CMS via the built in Ajax Framework

October CMS provides an extensive AJAX framework, that I'm looking to use to populate a Select2 box with.
According to Select2, using a remote dataset happens as follows:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
But from the October CMS docs, I cannot figure out how to pass the data to the server manually.
Questions are: which URL to use, and which parameters do I need to pass along so that October knows which function I want to access. Also, how can I capture the result without a partial being loaded?
This might be a trivial question; I might be looking in the wrong direction. Maybe the AJAX framework should not be used at all. Any insights on the correct way to proceed?
** EDIT FOLLOWING CORRECT ANSWER BY SAMUEL **
To make Select2 work with a remote dataset in combination with October CMS,
please take into account the following pitfalls. Below is my working code:
// SELECT 2
$('select').select2({
/*placeholder: "Your placeholder", // Remove this, this causes issues*/
ajax: {
// Use transport function instead of URL as suggested by Samuel
transport: function(params, success, failure) {
var $request = $.request('onSelect', {
data: params.data
});
$request.done(success);
$request.fail(failure);
return $request
},
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params);
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data,params) {
console.log(data);
return {
// The JSON needs to be parsed before Select2 knows what to do with it.
results: JSON.parse(data.result)
};
},
cache: true
},
minimumInputLength: 1
});
Below is the example output I used in combination with this Select2 example:
[
{
"id":1,
"text":"Henry Kissinger"
},
{
"id":2,
"text":"Ricardo Montalban"
}
]
Above JSON was generated by my VisitorForm.php file:
<?php namespace XXX\VisitorRegistration\Components;
use Cms\Classes\ComponentBase;
use XXX\VisitorRegistration\Models\Visitor;
use October\Rain\Auth\Models\User;
class VisitorForm extends ComponentBase {
public function componentDetails()
{
return [
'name' => 'Visitor Form',
'description' => 'Description of the component'
];
}
// The function that returns the JSON, needs to be made dynamic
public function onSelect() {
return json_encode(array(array('id'=>1,'text'=>'Henry Kissinger'), array('id'=>2,'text'=>'Ricardo Montalban')));
}
}
VoilĂ , hope this can be useful.
Pass the transport option instead of url. Here is an example:
$(".js-data-example-ajax").select2({
ajax: {
transport: function(params, success, failure) {
/*
* This is where the AJAX framework is used
*/
var $request = $.request('onGetSomething', {
data: params.data
})
$request.done(success)
$request.fail(failure)
return $request
},
dataType: 'json'
},
// ...
});

Select2(4.00) return undefined in onSelect event when useing ajax

I'm using Select2 (ver 4.00) and loading remote data with ajax method.
I need to retrieve title of selected option, but in select2:select event data is undifined
my code:
$(".js-data-action-terms").select2({
ajax: {
url: ajaxurl + "?action=terms",
dataType: 'json',
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: false
},
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
$('.js-data-action-terms').on("select2:select", function(e) {
console.log(e);
});
Result log:
In Select2 4.0.0, the selected object was moved from the evt.data property to evt.params.data. Now all extra data for events in Select2 is put in evt.params for consistency.

Select2 4.0 initial value in ajax mode

I have the following select on my page:
<select><option value="1" selected="selected">Caption</option></select>
I call select2 (v 4.0) init:
city.select2({
ajax: {
url: <...>,
data: <...>,
processResults: <...>,
cache: true
},
escapeMarkup: function(markup){ return markup; },
minimumInputLength: 0,
templateResult: function(repo){ return repo.name; },
templateSelection: function(repo){ return repo.name; }
});
The problem is that select2 is resetting default selected value and showing blank string. Is there any way to set default value on select2 init?
The issue was in your templateSelection method, as you are expecting a name property to be on your data object. Aside from the fact that text is now required and you wouldn't need the method if you re-mapped it, you aren't handling the case where the data object has a text property.
city.select2({
ajax: {
url: <...>,
data: <...>,
processResults: <...>,
cache: true
},
escapeMarkup: function(markup){ return markup; },
minimumInputLength: 0,
templateResult: function(repo){ return repo.name || repo.text; },
templateSelection: function(repo){ return repo.name || repo.text; }
});
This should fix your issue and display the initial selections properly.
The select2 docs now have an example of how to do this.
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
Basically, configure select2 for ajax and then pre-fill with the desired object. The magic is done in the last bit, .trigger() which causes select2 to pick up the change and render it.

Select2 JS Loading remote data with Ajax

I am using Select2 JS Version 4.0.0-rc.1 and having trouble loading suggestions with remote Ajax method.
Below are the markups and code
<select class="form-control input-sm" id="selFrame1" name="selFrame1">
<option> Select Frame </option>
</select>
the JavaScript Jquery
$('#selFrame1').select2({
ajax: {
url: siteUrl+"suggest/frames",
dataType: 'json',
delay: 250,
method:'POST',
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.result
};
},
cache: true
}
});
The Json Result returned by server
{results: [{"Code":"123360000"},{"Code":"123360358"},{"Code":"123364000"},{"Code":"123400000"}], more: false }
I am totally not sure if I need to write specific functions to show suggestions, the comments on the Ajax section say that we should not alter the result Json data.
Now somebody please tell me what more I should to get the code working to show the suggestions.
I guess with the new version of select2 a lot of stuffs have changed.
Your response is being returned as a Select2 3.x response, which is fine. We've provided the processResults method because of this (previously results) so you can modify the response on the client side.
In your case, your response includes the results key but your processResponse function is referencing a result key which does not exist. If you change it to something like
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.results,
pagination: {
more: data.more
}
};
},
Then things should start working. This also maps the existing more property on the response to the new pagination key that we migrated to in Select2 4.0.
Your Json response has to be like this :
{
"total_count":2,
"items": [
{"id":"01", "name":"item 1"},
{"id":"02", "name":"item 2"}
]
}
To work, you an id property.
Here is my config :
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = "<div class='select2-result-repository clearfix'><div class='select2-result-repository__img'><img src='" + repo.img + "' width='80' height='80' /></div><div class='select2-result-repository__meta'><div class='select2-result-repository__title'>" + repo.full_name + "</div>";
markup += "<div class='select2-result-repository__statistics'><div class='select2-result-repository__type'><i class='fa fa-flash'></i> Type : " + repo.type + "</div><div class='select2-result-repository__usecase'><i class='fa fa-eye'></i> Use case : " + repo.usecase + "</div></div></div></div>";
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name;
}
// Init select2
$(".select2").select2({
ajax: {
type : "GET",
url : "{{ path('tag_search_js') }}",
dataType: 'json',
delay : 250,
data : function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
placeholder: "Select a tag",
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
Hope this helps !

Categories