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
};
}
}
});
Related
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
I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
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.
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));
}
}
this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }