How to take multiple value when autocomplete with ajax in codeignator
view
<input type="text" class="form-control" name="" id="search">
<div id="result"></div>
ajax
$(document).ready(function() {
$("#search").autocomplete({
minLength: 1,
source: function(request, response) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/Admin/ajaxPro",
dataType: 'json',
crossOrigin: true,
type: 'POST',
data: {
search: request.term
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$("#result").append(
"<div>" + ui.item.value + "</div>"
);
},
});
});
controller
public function ajaxPro()
{
$term = $this->input->get('term');
// var_dump($term);
$this->db->like('business_name', $term);
$resultSet = $this->db->get("user_table")->result();
$data = [];
foreach($resultSet as $rs){
$data[] = $rs->business_name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
When I retrieve data using autocomplete, the only business_name is attached to the select: function Only the business name is available in the item .value, how do you get the corresponding value of the business name?
Please check the database
Now if I select the business name, how do I append the Email and rating in the result?
I'm trying to populate tags from DB into a select2 field. The data is returned in the inspect mode, but not populating in the select2 field.
I have a tags table with the tag_id and tag_name fields. The following is the code from the controller that fetches and returns the tags :
public function getTag()
{
$tag_list = DB::table('tags')
->select('t_name')
->get();
return response()->json(['tag_n' => $tag_list]);
The following is the Jquery that brings back the tags :
<script>
$(document).ready(function() {
$("#catBox").select2({
placeholder:"Select and search",
ajax:{
url: urlTag ,
type: 'GET' ,
dataType: 'json',
delay: 250,
data:function(params){
return{
tag_n:params.term
};
},
processResults:function(response){
return{
results: response
};
},
cache:true
}
});
});
</script>
The route and the route url :
<script>
var urlTag = '{{ route('getTag') }}';
</script>
Route::get('/gettag', [
'uses' => 'PostController#getTag',
'as' => 'getTag'
]);
The data is returned in the inspect mode, but not populating in the select2 field.
The following is the Select tag :
<select class="js-example-basic-multiple" multiple="multiple" name="catBox[]" id="catBox" style ="width:250px">
</select>
return data from a server like this:
[{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}] insted of pass with `{a_tag : [{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}]}`
$("#catBox").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
t_name: term
};
}
},
multiple: true,
ajax: {
url: urlTag ,
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
I have a select2 in a form in which I select a client, but if I return and change the selection once or more times to the database, all the concatenated names arrive.
In the HTML, I have the select2:
<select class="custom-select form-control-sm" id="inv_cntId" name="inv_cntId" required></select>
The script is like this:
$("#inv_cntId").select2({
placeholder: 'Seleccione un Cliente',
allowClear: true,
SingleSelection: true,
minimumInputLength: 3,
ajax: {
url: 'core/ContactSearch.php',
dataType: 'json',
delay: 50, //milisegundos
processResults: function (data) {
return {
results: $.map(data, function (obj) {
return {
id: obj.id,
text: obj.text,
address: obj.address
};
})
};
},
cache: true
}
});
How can I solve this behavior?
I am using Select2 with remote data. when i click on drop-down. no option will shows until write in search box.
But i want to show some data when drop-down open.
I am trying it with initselection or data but its initialize when data present in selected value.
$('.countrySelection').select2({
placeholder: "Select Country",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: base_url+'ajax_response/getCountry',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
$(".statenoSelect").select2("val", "");
$(".citynoSelect").select2("val", "");
var more = (page * 2) < data.page
return {
results: data.items,
more: more
};
},
cache: true
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax(base_url+'ajax_response/getCountry?id=' + id, {
dataType: "json"
}).done(function(data) { callback(data['items'][0]); });
}else{
$.ajax(base_url+'ajax_response/getCountry?default=true', {
dataType: "json"
}).done(function(data) { callback(data['items']); });
}
},
data:function(element, callback) {
callback(JSON.parse($(element).attr('data-selection')));
},
formatResult: repoFormatResult,
formatSelection: repoFormatResult,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
}).focus(function () { $(this).select2('open'); });
Its working with ajax, but how can I add options without search anything
Update:
I tried and spent alot of my time fixing the issue, and at last problem solved.
But initially Many Thanks to OnaBai and to my colleague who helped to come this far.
Now i am stuck here.
I type username and it show display on dropdown and after pressing TAB or ENTER it show the result in grid.
The result is only shown in grid if it is from page "1", but if it is from page "2" or any other further page the result is not shown.
Here is how it is working:
but when if i search for other user which is not on page 1 then it dont show display the other user in grid. instead i get empty grid.
FireBug screenShots:
Here is my Updated Code after i did some more changes in the code.:
<?php
/*foreach($users_list_data->result() as $row){
echo $row->Username."<br />";
}*/
?>
<div id="grid"></div>
<div id="details" />
<div class="second_column_content_container">
</div>
<script>
function create_user() {
var entryform = $("#insert_user_info");
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/createUser',
data : entryform.serialize(),
success : function(response) {
$(".second_column").html(response);
}
});
}
function create_user_form() {
$.ajax({
type : 'POST',
url : '<?php echo base_url(); ?>/index.php/user_management/manage_users/load_user_form',
success : function(response) {
$(".second_column").html(response);
}
});
}
function onChange(arg) {
var selected = "";
var grid = this;
grid.select().each(function() {
var dataItem = grid.dataItem($(this));
selected = dataItem.Username;
});
$.ajax({
type: "POST",
url: "<?php echo base_url()?>index.php/user_management/manage_users/get_user_groups/"+selected,
beforeSend: function(){
$("#pre_image").attr("src","http://localhost/zorkif_new/images/pre.gif");
},
success: function(output_string) {
$('.data_column_a').html(output_string);
}
});
}
var wnd, detailsTemplate;
$(document).ready(function(){
var serverBaseUrl = "<?php echo base_url(); ?>";
$("#grid").kendoGrid({
dataSource:{
serverPaging: true,
transport: {
read: serverBaseUrl + "index.php/user_management/manage_users/list_view/",
update: {
url: serverBaseUrl + "index.php/user_management/manage_users/userUpdate/",
type: "POST"
}
// destroy: {
// url: serverBaseUrl + "index.php/user_management/manage_users/userDelete/",
// dataType: "jsonp"
// }
//update: "<?php echo base_url() ?>index.php/user_management/manage_users/list_view/"
},
error: function(e) {
alert(e.responseText);
},
schema:{
data: "data",
total: "total",
model: {
id: "UserID",
fields: {
FirstName: { editable: true },
LastName: { validation: { required: true} },
MiddleNames:{validation:{required:true}}
}
}
},
pageSize:5
},
toolbar: kendo.template($("#toolbarTemplate").html()),
scrollable: true,
selectable: "row",
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{
field: "UserID",
hidden:true
},
{
field: "Username",
title:"Username"
},
{ field: "FirstName",
title:"First Name"
},
{field:"MiddleNames"},
{field:"LastName"},
{field:"City"},
{field:"Email"},
//{field:"Actions"},
//{command: { text: "Delete", click: showDetails }, title: " ", width: "140px"},
{command: { text: "Details", click: redirectToPage }, title: " ", width: "140px" },
{ command: { text: "Edit", click: redirectToEditPage }, title: " ", width: "140px" }
],
change: onChange,
editable: "popup"
});
$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Username",
dataSource: {
serverFiltering: true,
transport: {
read: {
type: "GET",
dataType: "json",
contentType:'application/json; charset=utf-8',
url: serverBaseUrl + "index.php/user_management/manage_users/search_user/",
data: function (arg){
//alert(arg);
//alert({Username:autocompleteUsers.data("kendoAutoComplete").value});
return {Username : $("#users").data("kendoAutoComplete").value()};
//return $("#users").data("kendoAutoComplete").value();
}
}
}
},
change: onChangeAutoComplete
});
function onChangeAutoComplete(){
var value = this.value();
var grid = $('#grid');
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "Username", operator: "Contains", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
/*$("#users").kendoAutoComplete({
minLength: 3,
dataTextField: "Title",
//JSON property name to use
dataSource: {
pageSize: 10,
//Limits result set
transport: {
read: {
url: "/echo/json/",
//using jsfiddle echo service to simulate JSON endpoint
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify([
{
"Title": "Doctor Who: The Trial of a Time Lord"},
{
"Title": "Doctor Who: The Key to Time"},
{
"Title": "Doctor Who: The Time Meddler"},
{
"Title": "Doctor Who: The End of Time"}
])
}
}
}
}
});*/
/*change: function () {
var value = this.value();
if (value) {
grid.data("kendoGrid").dataSource.filter({ field: "UserID", operator: "eq", value: value });
} else {
grid.data("kendoGrid").dataSource.filter({});
}
}
});*/
/*$("#users").blur(function() {
var data = $(this).data("kendoAutoComplete").dataSource._data,
nbData = data.length,
found = false;
for(var iData = 0; iData < nbData; iData++) {
if(this.value === data[iData].Title)
found = true;
}
console.log(found);
});*/
wnd = $("#details").kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
});
function redirectToPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/ViewProfile/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
function redirectToEditPage(e){
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/edit_user/'?>"+JSON.parse(item.UserID),
success: function(output_string){
$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
}
//show details on a popup
function showDetailsPopup(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
//This will redirect to Next Page
function showDetails(e) {
e.preventDefault();
var row = $(e.target).closest("tr");
var item = $("#grid").data("kendoGrid").dataItem(row);
$.ajax({
type: "POST",
url: "<?php echo base_url().'index.php/user_management/manage_users/list_view/'?>"+JSON.parse(item.UserID),
success: function(data){
alert("done");
//$('.second_column_content_container').html(output_string);
//$('.second_column_content_container').innerHTML("hello");
//alert(output_string);
},
error: function(data){
alert("error");
}
});
//var grid = $("#grid").data("kendoGrid");
//alert(JSON.parse(item.UserID));
//window.location.href="http://www.google.com/";
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName #</h2>
<h2>City: #= City # </h2>
</div>
</script>
<script type="text/x-kendo-template" id="toolbarTemplate">
<div class="toolbar">
<label class="category-label" for="users">Search Users: </label>
<input type="text" id="users" style="width: 250px;" />
</div>
</script>
<div class="data_column_a">
<img src="" id="pre_image" >
</div>
Now how to solve this very extremely difficult problem O_o??
Update:
This Username is on Page 2 of the Grid as can be seen in ScreenShot.
But during Search, it sends the headers of page 1 when i search for username that is other than of page 1.
Banging my head to walls, How to Solve ?
The problem seems to be related to you autocomplete definition that is not sending any Username argument on read. Try defining transport.read as:
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username : autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
},
EDIT: For applying selected value on autocomplete as filtering condition for the grid. You should do:
var autocompleteUsers = $("#users").kendoAutoComplete({
dataTextField: "Username",
dataSource : {
severFiltering: true,
transport : {
read : {
url : "search_user.php",
data: function (arg) {
return {Username: autocompleteUsers.data("kendoAutoComplete").value()};
}
},
dataType: "json",
type : "POST"
}
},
change : function () {
var username = autocompleteUsers.data("kendoAutoComplete").value();
var filter = {
logic : "and",
filters: [
{
ignoreCase: true,
field : "Username",
value : username,
operator : "startswith"
}
]
};
$("#grid").data("kendoGrid").dataSource.filter(filter);
}
});