I want to use select2 with data using ajax request. But its showing this error
Error: Option 'ajax' is not allowed for Select2 when attached to a <select> element.
HTML
<select id='myselect' class='select2-input select2'>
<option></option>
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
JS
$(document).ready(function() {
var base_url = $('#baseurl').val();
$("#myselect").select2({
placeholder: "Select a State",
allowClear: true,
ajax: {
url: base_url + 'selecttest',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.expense_detail,
id: item.user_id
}
})
};
}
}
});
Getting JSON Response Like this
[{"expense_id":"2","user_id":"5","expense_detail":"abcdh1","amount":"123","expense_date":"2016-10-18","expense_type":"pocket","team_code":"0","team_id":"0"},{"expense_id":"3","user_id":"5","expense_detail":"hxyz1","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"4","user_id":"5","expense_detail":"abch2","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"5","user_id":"5","expense_detail":"abh3","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"6","user_id":"5","expense_detail":"ah4","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"7","user_id":"5","expense_detail":"h5","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"}]
I'm using this select2 version
Copyright 2012 Igor Vaynberg
Version: 3.2 Timestamp: Mon Sep 10 10:38:04 PDT 2012
Any Help is much appreciated..Thank You.
Select2 expects the result to come with ID and TEXT attributes, Hence you you need to rewrite your results callback as,
results: function (data) {
var tmpResults = [];
$.each(data, function (index, item) {
tmpResults.push({
'id': item.user_id,
'text': item.expense_detail,
});
});
return {
results: tmpResults
};
}
Hope this helps
Related
I have a Dropdown created in Html as like this.
<label for="filter">Type:</label>
<select class="filter"
id="secquneceDropdownId">
<option value="" selected>All</option>
<option value="INSEQUENCE">In Sequence</option>
<option value="OUTSEQUENCE">Out Sequence</option>
<option value="RECIPES">Sequence Mapping</option>
</select>
I have tried to send selected value in jQuery as same as the Ajax JSON format. but I always get the null value in the backend.
Both ways are here,
Using jQuery:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.post("/IdeaOfThings/listSequences", {
isDropdownSelected : dropdownSelected
},
function(data, status) {
});
});
});
In Ajax format:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.ajax({
type: "POST",
url: '/IdeaOfThings//listSequences',
data: {isDropdownSelected: dropdownSelected},
dataType: "json",
success: function(data){
if(data.success==true){
alert('success');
}else if(data.success==false){
alert('Failed');
}
}
});
});
});
Why I`m getting null value as always.?
Maybe try changing
data: {isDropdownSelected: dropdownSelected}
to
data: {'isDropdownSelected': dropdownSelected}
html
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
-------------
jquery
$('body').on('click','#Customer_PO',function(e){
id_tosend=$(this).attr("id").toString();
var cust_id=$('#Customer_list').val();
var a=$('#'+id_tosend).select2({
ajax: {
url: 'ajax/report/inspection_report.php?cust_id='+cust_id,
dataType: 'json',
delay: 500,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data
};
},
cache:true
}
});
a.data('select2').dropdown.$dropdown.addClass("test");
$(this).select2('open');
});
i attach plugin of Select2 .When i submitted data in my form ,it shown me empty value . How i get this value to set selected initial value in ajax method.
you can try this
HTML
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
JQUERY
$.ajax({
url: 'url',
type: 'POST',
data: { id: id},
dataType: 'JSON',
success: function (resp) {
if(resp.msg == 'Done'){
$("#Customer_PO option:selected").removeAttr("selected");
$.each(resp.yourListData, function (key, value) {
$("#Customer_PO ").append('<option value="'+value.ID+'">'+value.name+'</option>');
});
$("#Customer_PO ").trigger("change", [true]);
}
},
error: function (e) {
console.log("Line 1204");
console.log(e.responseText);
}
});
I'm using select2 to show ajax results in a dropdown but when I append data to select2 its showing error
TypeError: b is undefined
JS Code
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
term.term contains the value of input text in dropdown search box.
HTML
<select class="myselect" style="width: 50% !important">
<option></option>
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
<option value="KY">Kentucky</option>
</select>
JSON RESPONSE
[{"id":9858,"firstname":"Testing3","status":2,"state":"VA","phone":""},{"id":9857,"firstname":"Testing2","status":2,"state":"VA","phone":""},{"id":9856,"firstname":" david polosky ","status":3,"state":"FL","phone":"(000)000-4141"}]
SELECT2 CDN LINKS
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
PHP SERVERSIDE CODE (LARAVEL)
$searchtext = $request->get('term');
$data = Inspector::latest('id')
->select('id', 'firstname', 'status', 'state', 'phone')
->where('firstname', 'LIKE', '%' . $searchtext . '%')
->get()->toArray();
echo json_encode($data);
Any help is appreciated.
In your ajax configuration you use results you should use processResults
Try this
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
processResults: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
Aamir#, sometimes errors are misleading. If you see from your code, it doesn't have a reference to b at all. I believe that must be an error that is being thrown from a method outside of your code, due to an error in your code.
You might have to set a break point by clicking on the line number on browser console and then check the call stack to find the error in the code.
I am stuck at problem where i believe i am getting the response in correct format but i am not able to display the data returned from the server. Intelligent Minds! I need your help.
Below is my HTML code:
<div class="form-group">
<select id="owner" class="dropDowns">
<option value="00000" selected="selected">Select Owner</option>
</select>
</div>
JQuery Code:
This function is getting called with no problems and a result is also returned from the server but some how i am not able to format that result and display it to the user. I am not sure what i am doing wrong and this has been bugging me for quiet some time now.
$("#owner").select2({
minimumInputLength: 3,
ajax: {
url: "http://localhost:8080/iam/aexp/rest/ePAAS/getOwner",
dataType: "jsonp",
headers: {
"Authorization": "Basic " + btoa('spadmin' + ":" + 'admin')
},
type: 'GET',
delay: 250,
data: function (params) {
return {
adsId: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
formatResult: function (data) {
return "<div>" + data.id + "</div>";
},
formatSelection: function (data) {
return data.id;
}
});
And here is the response I am getting from the server:
[{"id":0,"text":"rgadke"}]
Thanks!
I found the issue. I was not returning the result in the correct JSON format
I have tried a lot of ways to fix this problem.
At a dynamic list loaded via ajax, I can't make allowClear work.
Here is my jsFiddle
HTML:
<select id="first" class="init-select2" data-placeholder="First dropdown" data-allowclear="true">
<option></option>
<option>First option</option>
<option>Second option</option>
</select>
<select id="second" class="init-select2" data-placeholder="Second Dropdown" data-allowclear="true" disabled="disabled">
<option></option>
</select>
Javascript:
$(function() {
$('.init-select2').removeClass('init-select2').each(function(){
if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "true"){
$(this).select2({
allowClear: true
});
} else if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "false") {
$(this).select2({
allowClear: false
});
}
});
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {"json":JSON.stringify({"one":"first","two":"second","three":"third"})},
cache: false,
success: function(data) {
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({ allowClear: true });
});
}
});
});
});
in jsfiddle are already added the select2 javascript and css, please have a look there
Fixed by adding an "<option></option>" to second dropdown each time I change the value of first dropdown. See success handler below:
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"json": JSON.stringify({
"one": "first",
"two": "second",
"three": "third"
})
},
cache: false,
success: function (data) {
options.push("<option></option>");
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({
allowClear: true
});
});
}
});
});
Example of one of my own, as you can see I don't use "option" tags within my loop.
function companyURL() {
if ($.isNumeric($('#supplier_select').val())) {
return company_url + '/' + $('#supplier_select').val() + '/';
} else {
return company_url;
}
}
var results = [];
$('.company_select').select2({
ajax: {
url: function () {
return companyURL();
},
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
results.push({
id: '',
text: 'Select a company'
});
$.each(data, function (index, item) {
results.push({
id: item.company_id,
text: item.company_name
});
});
return {
results: results
};
}
}
});