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.
Related
I am using select2 dropdown and I am trying to build it as such that it dynamically displays the leads based on the JSON response.
As u can see in the image below, the text inserted correctly returns a JSON array, however, select2 is not capable of assigning the results into options. Therefore, I am literally quite stuck on what to do from here.
https://i.imgur.com/9OnvJzK.pnghere
I already tried setting a variable equal to the selectbox and appending the data in there, but my editor indicates that the code will be unreachable.
Create.tpl - contains front-end code
{literal}
<script>
$(document).ready(function() {
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
}
});
$('#select2lead').select2({
tags: true,
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
var query = {
search: params.term
};
// Query parameters will be ?search=[term]&type=public
return query;
},
processResults: function (data) {
var select2lead = $('#select2lead');
// Tranforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
}
// var option = new Option(data.name, data.id, true, true);
// select2lead.append(option).trigger('change');
}
}
});
$('#summernote').summernote({
height: 150,
minHeight: null,
maxHeight: null,
focus: true
});
})
</script>
{/literal}
ajax.php - handles the search term and returns JSON
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
$query = "
SELECT
LeadID AS lead_id,
REPLACE(CONCAT_WS(' ', LeadInitials, LeadInsertion, LeadLastName), ' ', ' ') AS name,
REPLACE(CONCAT_WS(' ', LeadStreet, LeadStreetNumber, LeadNumberAdjective), ' ', ' ') AS address,
LeadZiPCode AS zipcode,
LeadCity AS city
FROM
`LeadTBL`
WHERE
LeadID > 0
AND
LeadLastName LIKE :leadName
ORDER BY
LeadLastName
ASC
";
$binds = array(':leadName' => $_GET['term'].'_%'.'_%');
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['lead_id'], 'name'=>$row['name']];
}
echo json_encode($json);
Issue resolved. Turns out I had to disable "more"; See https://groups.google.com/forum/#!msg/select2/4mDifie32t0/jdJl8KIFN0EJ
Regarding the final code that actually pastes the results into the dropdown properly, see:
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajax.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
I have been having a little problem. I am trying to create a filter for my database. So far I have come up with this:
Blade File:
<input type="text" class="form-control" id="search" name="search" placeholder="Name, NORAD or ID"></input>
<select name="filtername" id="filtername">
<option value="none"></option>
<option value="Falcon">Falcon</option>
<option value="rb">R/B</option>
</select>
Javascript AJAX Call:
$(document).ready(function() {
$('#search').on('keyup', function() {
$value = $(this).val();
delay(function() {
if ('#search'.length > 3) {
$.ajax({
type: 'get',
url: '{{$launchsitename->site_code}}',
data: {
'search': $value
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
}
}, 300);
});
$("#filtername").change(function() {
var filtername = $(this).val();
var dataString = "filtername=" + filtername;
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
});
Controller:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->where(function($q) use ($request) {
$q->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
->orWhere('object_id','LIKE','%'.$request->search.'%');
})
->where('site', $site_code)->get();
if ($launchsitesatellite)
{
$output .='<tr>'.
'<th>'.'Satellite Name'.'</th>'.
'<th>'.'NORAD ID'.'</th>'.
'<th>'.'Object Type'.'</th>'.
'<th>'.'Launch Date'.'</th>'.
'<th>'.'Country'.'</th>'.
'<th>'.'Object ID'.'</th>'.
'<tr>';
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'<td>'.$launchsitesatellites->launch.'</td>'.
'<td>'.$launchsitesatellites->country.'</td>'.
'<td>'.$launchsitesatellites->object_id.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->Paginate(40);
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
This code is for making an AJAX call to my controller and getting the results from the database. The code posted above works perfectly for the input. I am able to search the database with ease. The only problem is with the select. Whenever I select an option, it returns no results. I am guessing there is something wrong with the way I programmed the select in my controller, as I don't think the Javascript would be causing the problem.
The select should be reading the satname column in my database called satellites and returning the filtered results.
Would somebody be able to shed some light on why the select is not working or where the error in my code is?
modify your ajax call code for select box as below
$("#filtername").change(function() {
var dataString = $(this).val();
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
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
Sorry, but can't find a resolve.
Whenever i try to do some searching, select2 will show 'The results could not be loaded'.
I think my ajax settings is wrong
html:
<select class="js-data-example-ajax form-control" multiple="multiple"></select>
script:
$(".js-data-example-ajax").select2({
ajax: {
url: '#Url.Action("LoadCity", "Addresses")',
dataType: 'jsonp',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1,
});
screen
ADD 08.07.2016
some change ajax settings:
dataType: 'jsonp'
to
dataType: 'json'
and add
type: 'GET',
now no message 'The results could not be loaded', and no results
Base from you last comment. The process result should return an object that has a results key.
So it should be:
return {
results: [{id: 1, text: 'Test'}]
}
I recently encountered the exact same problem using version 4.0.5
This is a known bug in the component solved starting with version 4.0.6
From Github official repository:
Fix AJAX data source error #4356
Updating my local version of the select2 component solved the issue.
I have this working select2, I have implemented this yesterday, It might help you.
select2_common('.accounts','Account & Description');
function select2_common(selector,placeholder)
{
$(selector).select2({
minimumInputLength:2,
placeholder:placeholder,
ajax: {
url: "your_url_here",
dataType: "json",
delay: 200,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data) {
// console.log(data);
return {
results: $.map(data, function(obj) {
if(obj.id!=0){
// console.log(obj);
return { id: obj.id, text: obj.name };
}
else
{return {id: obj.id, text: obj.name}}
})
};
},
cache: true
},
debug:false
});
}
//And your result should be in this form, from your method....
//I am using laravel php framework.
public function getAccountDetail(Request $request)
{
$q = $request->input('q');
$result=[];
if (isset($q) && $q != '') {
/*---------- Search by account code or title ----------*/
$data = DB::table('acc_accounts')->select('acc_id','acc_code','acc_title')
->where('acc_code', 'like', '%' . $q . '%')
->orWhere('acc_title', 'like', '%' . $q . '%')
->limit(10)->orderBy('acc_code')->get();
foreach ($data as $key => $value) {
$new1 = array('id' => $value->acc_id, 'name' => $value->acc_code.' ('.$value->acc_title.')' );
array_push($result,$new1);
}
print(json_encode($result));
}
}
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
};
}
}
});