Select2 - Ajax search - remember last results - javascript

I am using Select2 3.5.1. With this plugin I can successfully load remote data. However I am here today to ask a question to improve this search. Here is the step-by-step to understand what I would like to do:
Setup a Select2 with remote data loading (using ajax).
Click on the Select2 input and search for something.
The loading will appear and after some seconds you will see a list of results.
Click on one of the results listed - the box of results will then disappear.
If you click again on the search box, the list will be empty and you will need to type some new text again to have a list of results.
Is it possible that when we click again on the search box, that the list of results previously searched re-appear without any ajax call? Then if the user delete a character or change his search criteria it would then trigger the ajax search again.
If it is possible, how would we code that?
I hope my question is clear, please let me know if you have any questions. Thank you.
Here is a very simple code where we do a search that return a list of results. It doesn't really search, but it does return a list when you type something. I am not sure how to use the initSelection that is mentionned in one of the response.
<html>
<head>
<title>
Test page for ajax cache
</title>
<script type='text/javascript' src='../../resources/javascript/jquery/jquery-1.9.1.min.js'></script>
<link type='text/css' href='../../resources/javascript/select2/select2.css' rel='stylesheet' />
<script type='text/javascript' src='../../resources/javascript/select2/select2.js'></script>
<script>
$(document).ready(function(){
$('#select').select2({
ajax: {
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: function(term, page){
return {
autoc: 'country',
term: term
}
},
results: function(data, page){
console.log(data);
return( {results: data.results} );
}
},
placeholder: 'Search something',
minimumInputLength: 3,
width: '333'
});
});
</script>
</head>
<body>
<input type='text' name='inputdata' id='select' />
</body>
</html>
The very simple ajax.php called:
<?php
$results2['more'] = false;
$results2['results'][0] = array('id'=> "1", 'text'=> "California");
$results2['results'][1] = array('id'=> "2", 'text'=> "Canada");
$results2['results'][2] = array('id'=> "2", 'text'=> "Someword");
$results2['results'][3] = array('id'=> "2", 'text'=> "Alberta");
$results2['results'][4] = array('id'=> "2", 'text'=> "New York");
echo json_encode($results2);

I did read your post once again.
I misunderstood you last time.
The solution is here.
$(document).ready(function () {
$('#select').select2({
// this part is responsible for data caching
dataCache: [],
query: function (q) {
var obj = this,
key = q.term,
dataCache = obj.dataCache[key];
//checking is result in cache
if (dataCache) {
q.callback({results: dataCache.results});
} else {
$.ajax({
url: 'ajax.php',
data: {q: q.term},
dataType: 'json',
type: 'POST',
success: function (data) {
//copy data to 'cache'
obj.dataCache[key] = data;
q.callback({results: data.results});
}
})
}
},
placeholder: 'Search something',
width: '333',
minimumInputLength: 3,
});
// this part is responsible for setting last search when select2 is opening
var last_search = '';
$('#select').on('select2-open', function () {
if (last_search) {
$('.select2-search').find('input').val(last_search).trigger('paste');
}
});
$('#select').on('select2-loaded', function () {
last_search = $('.select2-search').find('input').val();
});
});

This will make another ajax call but with the same query string as before. Uses event select2:closing to save last query string and select2:open to insert the string into the search input and trigger input event.
var lastQueryString = '';
jQuery(".my-select2").select2({
minimumInputLength: 2,
placeholder: "Select an option",
ajax: {
url: "/example",
data: function (params) {
var query = {
search: params.term
}
return query;
},
processResults: function (data) {
return {
results: JSON.parse(data)
};
}
}
});
jQuery('.my-select2').on('select2:open', function () {
if (lastQueryString) {
jQuery('.select2-search').find('input').focus().val(lastQueryString).trigger('input');
}
});
jQuery('.my-select2').on('select2:closing', function () {
lastQueryString = jQuery('.select2-search').find('input').val();
});

Related

select multiple values in select2 using javascript

I need to pass value from select2 to javscript. But its not working.
this is my html code
<select class="txtTeamAddDelete form-control" name="itemName"></select>
</div>
<button type="button" class="btnrowAddDelete">Add New Row</button>
This is my javascript select2
<script type="text/javascript">
$('.txtTeamAddDelete').select2({
placeholder: 'Select an item',
ajax: {
url: "{{route('meeting.list-meeting.dataAjax')}}",
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id,
email: item.email
}
})
};
},
cache: true
}
});
</script>
this is js for display select2 data
$(document).ready(function(){
$('.btnrowAddDelete').click(function(){
var txtTeamAddDelete = $('.txtTeamAddDelete').find(':selected').text();
$('.TableAddDelete tbody').append("<tr><td>"+txtTeamAddDelete+"</td><td>"+email+"</td></tr>");
});
});
its working to fetch name data but not email. I want to fetch two data: email & name. i already tried this
var txtTeamAddDelete = $('.txtTeamAddDelete').select2('val',["name", "email"]);
but it return undefined
i want to show it like this. can someone help me. Thanks!

How can I fill all data in select2 (4.0) when page loaded?

I am using select2 plugin (v.4.0).
What I am trying to do:
$("#search-input-chains").select2({
placeholder: "Unit",
theme: "bootstrap4",
allowClear: true,
initSelection: function (element, callback) {
callback({id: 1, text: 'Text'});
},
ajax: {
url: function () {
return getURLForFilial();
},
dataType: 'json',
delay: 250,
processResults: function (response) {
console.log(response);
return {
results: response
};
},
cache: false
}
});
function getURLForFilial() {
return '/user/rest/data/entry/units/branches?type=1';
}
I need to understand, whether my control has data retrieved from DB or not, and if there is no data - this select list shall not be activated.
I found how I can understand the data amount:
$("#search-input-chains").data().select2.results.$results[0].childNodes.length
(maybe there is another way that is much better?)
But this piece of code returns 0 until I will activate (click) on the select2 box and trigger AJAX request to find data.
I read a lot about how can I perform the pre-call off AJAX, but it doesn't work.
I tried to trigger event on select2 in such a way:
$("#search-input-chains").val().trigger('change');
Please, advice, how can I load data to my select2 control with the page load to understand whether I need to disable this select or not?
I've made it via AJAX:
ajax({
type: 'GET',
url: '/user/rest/data/entry/units/branches?type=1'
}).then(function (data) {
if (data.length !== 0) {
chainsSelectElement.prop("disabled", false);
chainSelectorHasData = true;
} else {
// create the option and append to Select2
let option = new Option('Nothing', 'null', true, true);
chainsSelectElement.append(option);
chainSelectorHasData = false;
chainsSelectElement.prop("disabled", true);
}
getDataForSubdivisions();
});

Select2 AJAX not showing "No data found" when no data in database, instead showing search parameter as option to select

I've been working on a project where I've to load select2 option from ajax call.
The code is working fine, except in search result, it always shows search parameter as option. Even if there is no data in database, it still showing it as option, not showing "No data found".
My code is here
$(".search_user").select2({
minimumInputLength: 11,
tags: [],
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});
my return json is like this
{"item":[{"id":16,"name":"Razin Abid"}]}
My view is looking like this.
Please help me out.
If you using firemodal on stisla
$('#modal-create-promo').click(()=>{
setTimeout(()=>{
$('#fire-modal-1').removeAttr('tabindex');
});
});
$("#modal-create-promo").fireModal({
...
});
It's work for me
Thats because you enable tags option from select2. You need to remove 'Tags:[]' from your code.
visit : https://select2.org/tagging
so, your code should be like this:
$(".search_user").select2({
minimumInputLength: 11,
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});

Select2: Creating tags with ajax

I am using the select2 library.
My select2 element can search the database for each tag via the ajax and that works fine.
My issue is, I want the user to also be able to create a new tag. Looking at their documentation I should use the createTag option; however, this fires as soon as I click into the element and on each key press.
Can anyone offer any guidance on how I can achieve my goal?
here is my code thus far
I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST.
}
});
After reading the documentation again, I can see I should have been using the events https://select2.org/programmatic-control/events
I used the createTag option to assign newTag: true to newly created tags and used the select2:selected event which checked if a new tag had been selected and, if it was, sent an ajax request to the server to create that tag.
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

Categories

Resources