I am using Select2 4.0.1, I have used ajax to populate the result based on users input, but whenever I search for anything select2 lists first page result, but consecutive pages were not loading, also request is made for 2nd page on scroll. seems to be I am missing something.
$multiselect = $(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, params) {
var more, new_data;
params.page = params.page || 1;
more = {
more: (params.page * 20) < data.total_count
};
new_data = [];
data.items.forEach(function(i, item) {
new_data.push({
id: i.name,
text: i.name
});
});
return {
pagination: more,
results: new_data
};
},
cache: true
}
})
Any help is much appreciated.Thnx:)
This is the code I got working last week. I am using a different transport on my end, but that shouldn't make a difference. I was having the same issue as you regarding the lack of paging working while scrolling. My issue ended up being that I didn't have the proper {'pagination':{'more':true}} format in my processResults function. The only thing I can see that may work for you is to "fix" the page count in the data function vs. the processResults function.
When you scroll to the bottom of your list, do you see the "Loading more results..." label? Have you attempted to hard code the more value to true while debugging?
this.$(".select2").select2({
'ajax': {
'transport': function (params, success, failure) {
var page = (params.data && params.data.page) || 1;
app.do('entity:list:search',{'types':['locations'],'branch':branch,'limit':100,'page':page,'term':params.data.term})
.done(function(locations) {
success({'results':locations,'more':(locations.length>=100)});
});
}
, 'delay': 250
, 'data':function (params) {
var query = {
'term': params.term
, 'page': params.page || 1
};
return query;
}
, 'processResults': function (data) {
return {
'results': data.results
, 'pagination': {
'more': data.more
}
};
}
}
, 'templateResult': that.formatResult
, 'templateSelection': that.formatSelection
, 'escapeMarkup': function(m) { return m; }
});
Related
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;
};
I'm using the following code to fetch options from a database and populate a select2 on open. It works pretty well, but as soon as I start typing in the select2 search input box it also searches via the same ajax function. How can I just populate every time it opens, but then leave it there as long as it's opened?
Also since I'm using it to create tags I lost the ability to auto-select the new tag when I attached the ajax part, so instead of typing and pressing enter to add a tag, it's now stuck in search-land and I have to click on the newly created tag manually if I want it to be selected.
Any ideas?
function formatMenu (data) {
if (!data.id) { return data.text; }
var $data = $(
'<nobr>' + data.text + '</nobr>'
);
return $data;
};
$('select').select2({
templateSelection: formatMenu,
dropdownCssClass: 'select2-menu',
dropdownParent: $('#parent'),
placeholder: '-',
tags: true,
allowClear: true,
ajax: {
url: "?ajax=get_data,
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: false
},
sorter: function(data) {
return data.sort(function (a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
},
createTag: function (params) {
return {
id: params.term,
text: params.term
}
}
});
I am using Select2 4.0.1 with mCustomScrollbar,
I have used ajax to populate the result based on users input, but whenever I search for anything select2 lists first page result, but consecutive pages were not loading, on reaching end of the scroll 2nd page request is not sent.
$multiselect = $(element).select2({
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,
page_limit: 20
};
},
processResults: function(data, params) {
var more, new_data;
params.page = params.page || 1;
more = {
more: (params.page * 20) < data.total_count
};
new_data = [];
data.items.forEach(function(i, item) {
new_data.push({
id: i.name,
text: i.name
});
});
return {
pagination: more,
results: new_data
};
},
cache: true
}
}).on('select2:open', function(e){
function showScroll() {
$(element).siblings(".tag-multiple-dropdown").find('ul').mCustomScrollbar("destroy");
$(element).siblings(".tag-multiple-dropdown").find('ul').mCustomScrollbar(
{ mouseWheel:true,
advanced:{
updateOnContentResize: true
}
});
}
setTimeout(showScroll, 1000);
});
Any help is much appreciated.Thanks :)
Good day,
I was in some disarray . I have a ajax request from select2. Also I have two urls. How should I event organized If / else success/failure statements, if suddenly one will not work , then send an inquiry to another link?
I'm trying again and again and alwas there is error somewhere((
$(".js-data-example-ajax").select2({
language: "ru",
placeholder: "Serach.........",
disabled: false,
selected: true,
ajax: {
url: "url_1",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term + "%", // search term
};
},
processResults: function (data) {
if (data.features.length > 0) {
var resultArray = [];
$.each(data.features, function (index, value) {
value.attributes.id = value.attributes.OBJECT_ID;
resultArray.push(value.attributes);
});
return {
results: resultArray
};
} else {
return []
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 5,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
It should be quite simple because you only have to call the first url and, on error, call the second.
$.ajax(function(data){
url: "url_1",
...,
success(function(data){
//do stuff on success
}),
error(function(e){
$.ajax(function(data{
//call the second url
})
})
})
I'm trying to set datas from ajax in a select2 select...
But the problem is that if I write something which isn't in my datas i can select this choice !
And this will take this value "I don't exist" ... The formatNoMatches() function seems not to be called ...
JS :
$(".select2-ajax").select2({
ajax: {
url: "ajax.call.php",
type:'POST',
dataType: 'json',
data: function (params) {
return {
nom: params.term, // search chars
page: params.page,
};
},
processResults: function (data, page) {
console.log(data.data);
if(typeof(data.data)=='undefined' || !data.data || data.data.length <= 0)
var res = [];
else
{
var res = [];
for (var i = data.data.length - 1; i >= 0; i--)
{
res.push({"text":data.data[i]["nom"]+' '+data.data[i]["prenom"],"id":data.data[i]["id_salarie"]});
};
}
return { results: res};
},
cache: true
},
formatNoMatches: function( term ) {
return "<li class='select2-no-results'>' "+term+" ': Aucun résultat</li>";
},
allowClear: true,
language: 'fr',
multiple: false,
I tried the two following after seeing THIS question : ( but still don't work )
selectOnBlur:false,
createSearchChoice: false,
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
});
This should only happen if you are returning an option from your server that matches the text the user entered or you are using the tags option.
Since you don't appear to be using tags, and your code doesn't include it, you can ensure this is not the issue by overriding createTag (previously createSearchChoice to always return null.
$('select').select2({
createTag: function () {
// Disable tagging
return null;
}
});
Set tags to false. Example:
$('select').select2({
tags: false
});