How to Select Multiple Value in Autocomplete in CodeIgniter using ajax - php

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?

Related

Posting the input value with tag in the background

I want it to be posted as an id in the field that users see, but when posting.
https://prnt.sc/z5Hw61LuKoGy -> the area the user sees
https://prnt.sc/plR-s1eb4OGE -> Id data sent with value tag in background
When I post like this, I see it as 0 in my database.
https://prnt.sc/XjPHKrthej2M
Why not 4?
Can you help me?
I am using jQuery UI Autocomplete.
MY JQUERY CODE
$("#urun_olustur .col-10 input").autocomplete({
source: function(request,response){
$.ajax({
url: 'ajax.php',
type: 'post',
dataType: 'json',
data: {
search: request.term
},
success: function(data){
response(data);
}
});
},
select: function(event,ui){
$(this).val(ui.item.label);
$(this).attr("value",ui.item.value);
return false;
}
});
MY AJAX.PHP CODE
if (isset($_POST["search"])) {
$search = $_POST["search"];
$query = $db->query("SELECT * FROM test WHERE test_name LIKE '%".$search."%'");
$response = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$response[] = array(
"value" => $row["id"],
"label" => $row["test_name"]
);
}
echo json_encode($response);
exit;
}
You can get like this I have add following snippet please check.
I have take the change event you can use any other required event as per your convenience
$("#ac_text_id").on('autocompletechange change', function() {
$('#ac_text_op').html('You selected: ' + this.value);
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control ui-autocomplete-input" name="ac_text" id="ac_text_id" autocomplete="off" value="4">
<div id="ac_text_op"></div>

Can't attach data to select2 option

I want to make edit form and attach data from database to select2 option. In insert form this select2 option search data in database when we type word by word. I can't attach the data in this select2 option. I want to make this select2 option is fill with the data from database and also can change the data like in insert form. I already try $('#requestor').val($row['requestor']); but the data doesn't appear. Can anyone help me???
<select class="requestor form-control" name="requestor" id="requestor" style="width:700px" required="required">
<option value=""></option>
</select>
//search data in database word by word
$('.requestor').select2({
placeholder: 'Requestor Name',
ajax:{
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
dataType: "json",
delay: 250,
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.FullName,
option_value:item.ID
});
});
return{
results: results,
cache: true,
};
},
}
});
function load() {
alert('ok');
//console.log(<?php echo $row['ID']; ?>);
if (<?php echo $row['ID']; ?> != '') {
$('#requestor').val($row['requestor']);
}
}
window.onload = load;
Thank You :)
Your code is very messy. Be more clear like this:
<div class="col-md-12">
<select style="width:100%;" name="requestor[]" id="requestor" class="select2-multiple" multiple></select>
</div>
Then:
var $ajax = $("#requestor");
$ajax.select2({
ajax: {
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return{
search: params.term
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data
};
},
cache: true
},
language: "en",
placeholder: "Requestor Name",
allowClear: true,
minimumInputLength: 3,
maximumSelectionLength: 1,
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
var markup = repo.text ;
return markup;
}
function formatRepoSelection (repo) {
return repo.Name.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");
}
Your Ajax data must be have this format:
data[0]['ID'] = 1; //You must have "ID" key
data[0]['Name'] = 'Name'; //You must have "Name" key
It's easy that's it!
Good luck.

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

Autocomplete dropdown

I have an autocomplete search bar to search employee names.
Index.php
<script>
$(document).ready(function() {
$('input.employees').typeahead({
name: 'employees',
remote: 'mysql.php?query=%QUERY'
});
})
</script>
<form><font color='black'>
<input type="text" name="employees" class="employees" placeholder="Search Employees...">
Autocomplete.php
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '%{$query}%' OR name_last LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'label' => $row['name_first'].', '.$row['name_last'],
'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
}
This is working fine. However I would like to be able to click a result in the dropdown and go to another page. This needs to include one of the variables, employee_id. E.g http://example.com/new-page.php?id=employee_id
Is this possible?
You can do it with jQuery-ui autocomplete widget.
After adding jquery-ui's javascript and css files, write the code like this:
$('.employees').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
url: "Autocomplete.php",
data: "{'query':'" + request.term + "'}",
success: function (data) {
response($.map(data, function (item) {
return {
value: item.value,
id: item.employee_id,
label:item.label
}
}))
}
})
}
}).data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('' + item.label + '')
.appendTo(ul);
}

I need an expample of jQuery Autocomplete returning id and name using ajax

I need an example of how to code a jQuery autocomplete to populate product_id while showing the product_name calling an ajax page "remote.php"
<input name="product_name" id="product_name" type="text" value="" />
<input name="product_id" id="product_id" type="hidden" value="" />
remote.php:
$partial = addslashes($_POST['partial_search']);
$myDataRows = array();
$result = mysql_query ("SELECT product_id, product_name FROM products
WHERE product_name like "%$partial%");
while ($row = mysql_fetch_row($result)) {
array_push($myDataRows, $row);
}
$ret = json_encode ($myDataRows);
echo $ret;
I'm not sure how to code the jQuery autocomplete and if I need to change remote.php
thanks
ADDED LATER:
I worked out another solution:
<script type="text/javascript">
function nqi_search (type, id_name, text_name)
{
$( "#"+text_name ).autocomplete({
source: "remote.php?&t="+type,
minLength: 1,
select: function( event, ui ) {
$( "#"+id_name ).val(ui.item.id );
}
});
}
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
nqi_search ("product_search", "product_id", "product_name");
// also you can have many on one page with:
nqi_search ("vendor_search", "vendor_id", "vendor_name");
});
</script>
There's one problem. it doesn't seem to work if the nqi_search function is put into a .js file. I have no idea why?
This is how I do it:
Note, I've coded a special feature where the json can flag an item as a message instead and in this way you can put messages in the list (eg I put a "Addition X items not shown" for long lists). To use the message feature, but the text in the label field and a true boolean for the message field.
To use this on the page I just have
setupAutocomplete(<id of textbox>,<path to service>);
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(msg) {
$('#error').html(msg.responseText)
}
});
// remove this to get rid of custom message handling
$.widget("custom.redcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this;
$.each(items, function(index, item) {
if (item.message)
ul.append("<li class='ui-menu-item special-red'> " + item.label + "</li>");
else
self._renderItem(ul, item)
});
}
function setupAutocomplete(inID, inURL) {
var myTB = $("[id$='_" + inID + "']");
// change redcomplete to autocomplete to get rid of message handling
myTB.redcomplete({
source: function(request, response) {
$.ajax({
url: inURL,
data: "{'filter': '" + request.term + "'}",
success: function(data) {
response($.map(data, function(item) {
return {
label: item.text,
value: item.id,
// remove this line and the , above to get rid of message handling
message: item.message
};
}));
}
})
},
delay: 500,
minLength: 3,
focus: function(event, ui) {
myTB.val(ui.item.label);
return false;
},
select: function(event, ui) {
// action for the select here.
return false;
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

Categories