Fill a select options with Select2 Ajax - javascript

I'm using Select2 Ajax to apply autocomplete on my html select
this is the select2 code :
<script>
$(function(){
$(".marques-multi").select2({
minimumInputLength: 3,
tags: [],
ajax: {
url: "user/marques",
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return term;
},
processResults: function (data) {
return {
results: data
};
},
transport: function (params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
});
});
</script>
and this is my html :
<select class="form-control input-sm marques-multi" name="marque"></select>
and this is what the URL : "user/marques" with the data (www.mywebsite.com/user/marques/marques?term=nike) returns :
[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]
when I write as example nik in the select input i see in the console that the requests returns this json bellow with no errors but the select doesn't get fill with this data it stays blank.

If possible, change your data properties on JSON from id_marque and marque_name to id and text instead.
So from:
[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]
To:
[{"id":"50670","text":"NIK HUBER GUITARS"},{"id":"50671","text":"NIKALAS CATLOW"},{"id":"1","text":"NIKE"},{"id":"50672","text":"NIKE"},
{"id":"50673","text":"NIKE"},{"id":"50674","text":"NIKE 6.0"},{"id":"50675","text":"NIKE ACCESSORIES"},{"id":"50676","text":"NIKE ACG"},{"id":"50677","text":"NIKE ACTION SPORTS"},{"id":"50678","text":"NIKE AIR MAX"},{"id":"50679","text":"NIKE BAIN"}];
Fiddle

Related

how to dynamic function use ajax jquery in select2

so I use this code to make everything that has the $(".select2") element will process ajax according to the rest of the data sent via html
$(".select2").each(function () {
let element = $(this);
element.select2({
theme: "bootstrap",
placeholder: element.data("placeholder"),
ajax: {
url: element.data("url"),
dataType: 'json',
delay: 100,
cache: true,
data: function (params) { return { q: params.term } },
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
text: item.bank_name, /***** this *******/
id: item.id /***** this *******/
}
})
};
}
},
});
})
I've added element.data ("placeholder") and element.data ("url") in jquery, while how to send it with this html code
<select id="bank_id" name="bank_id"
class="fetch_bank form-control select2"
data-placeholder="Choose Bank"
data-url="/api/bank/fetch">
</select>
sending it ajax will return the following results
{
code: 200
error: false
message: "loaded!"
results: [
{id: 1, bank_name: "AMERICAN EXPRESS BANK LTD"},
{id: 2, bank_name: "ANGLOMAS INTERNASIONAL BANK"},
....
]
}
I have 3 records that return json, to display to select2, the column is as below
Bank(id, bank_name)
School(id, school_name)
Status(id, status)
but the problem is, how do i make 'processResults' dynamic? which I have marked with a comment / ***** this ******* /
While the 3 data has different keys, how do I make the select2 function dynamic?
thanks, I hope someone answers my question :)

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
}
}
}
});

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);
}
})
}
});

How to use select2 plugin with php and ajax?

I am new to select2 plugin, my problem is,
I want to put a job search option to my web page that is when user queries with keyword php then it will return corresponding data as json. For example if user enters java then it will return most possible words like java, javascript, java.net and user can pick up one or more item from the list displayed.
i did but there is no select option
script
$(".load").select2({
minimumInputLength: 2,
ajax: {
url: "http://localhost/testserver/Test",
dataType: 'json',
type: "post",
data: function (term, page) {
return {
q: term
};
},
processResults: function (data, page) {
console.log(data);
return {
results: $.map(data, function (item) {
return {
text: item.Name,
}
})
};
}
},
});
html
<select class="load" style="width:400px;">
Find below Complete solution
$(document).ready(function() {
$(".load").select2({
minimumInputLength: 2,
ajax: {
url: "http://ip.jsontest.com/",
dataType: 'json',
type: "post",
data: function (term, page) {
return {
q: term
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) { console.log(item);
return {
text: item
}
})
};
}
},
});
});
I have pointed url to some other location for dynamic data..Please make changes accordingly

Set selected value on select2 without loosing ajax

I have this select2 code in my html (mvc with razor) page:
$('#QuickSearchState').select2({
minimumInputLength: 3,
width: 'resolve',
ajax: {
url: '#Url.Action("QuickSearchState", "DataCenter")',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
traditional: true,
quietMillis: 400,
data: function(term, page) {
var data = {
term: term
};
return data;
},
results: function(data, page) {
return { results: data };
}
},
initSelection: function(element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
},
formatResult: function(format) {
return format.label;
},
formatSelection: function(format) {
//this is a knockout view model
vmNewAddress.IdState(format.id);
vmNewAddress.StateName(format.stateName);
return format.label;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) { return m; }
});
But i have another select in my code that can set a state in this select, but i dont know how to set this value to that select.
In my html i have this:
<select class="width-xl" data-bind="options: vm.GivenLocationsForConnection, optionsText: 'DisplayFormat', value: SelectedLocation"></select> -> first select that can fill the second state search select with a state
#Html.Hidden("query", null, new { #id = "QuickSearchState", #class = "width-xl", placeholder = "Ej. Montevideo" }) -> second select, this is a search for states and selects a single state
I am not sure if this is what you want but if you only want to select a value in the select you can just do below
$("#QuickSearchState").select2("val", "<YOUR VALUE>");

Categories

Resources