Select 2 "ajax results could not be loaded" - javascript

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

Related

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

Populate Select2 from function call with AJAX

I want to populate a select2 dropdown with an AJAX response function with data that will be called whenever the dropdown required for it changes value. I console logged to be sure that the function gets reached, but nonetheless, the instructions are not being ran by the machine:
create.tpl - Holds front-end code
$('.select2lead').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxLeadSearch.php',
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term
};
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
$('.select2lead').on("change", function() {
var value = $(this).val();
// console.log(value);
searchProjectsByLeadID(value);
});
function searchProjectsByLeadID(id){
$('.select2project').select2({
minimumInputLength: 3,
ajax: {
type: 'GET',
url: '/modules/support/ajaxProjectSearch.php',
dataType: 'json',
delay: 250,
data: {
"id": id
},
processResults: function (data) {
return {
results: data,
more: false
};
}
}
});
console.log(id);
}
ajaxProjectSearch.php
<?php
require_once('../../config.php');
$login = new Login();
if (!$login->checkLogin()) {
echo lang($_SESSION['language'], "INSUFFICIENT_RIGHTS");
exit();
}
$db = new Database();
// Select the projects
$query = "
SELECT
ProjectID AS project_id,
ProjectSummaryShort AS project_summary,
FROM
`rapports_projectTBL`
INNER JOIN LeadTBL ON rapports_projectTBL.LeadID=LeadTBL.LeadID
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
ORDER BY
ProjectID
ASC
";
$binds = array(':leadId' => $_GET['id']);
$result = $db->select($query, $binds);
$json = [];
foreach ($result as $row){
$json[] = ['id'=>$row['project_id'], 'text'=>$row['project_summary']];
}
echo json_encode($json);
Network output in console
https://i.imgur.com/6ZmGGxa.png
*As we can see, the searchProjectsByLeadID(id) function gets called but we get nothing back. No errors nor any values. The only thing getting transported is the first select box, which fetches lead data upon whats typed in the searchbox. *
RESOLVED
Issue was called by having the SQL query looking for a LIKE rather than a DIRECT MATCH:
WRONG
WHERE
ProjectID > 0
AND
rapports_projectTBL.LeadID LIKE :leadId
CORRECT
WHERE
rapports_ProjectTBL.LeadID=:leadId

How to append ajax data into select2

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

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

Select2 TypeError: b is undefined

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.

Categories

Resources