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);
}
Related
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>
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?
below is my autocomplete textbox code..
code is working fine..
But I also need to store id of selected value in hidden textbox ..
FOR EX =
there are 2 values coming in my auto textbox
id societyname
7 raj
15 lucky
ok if i select raj from above value then display id of raj ie : 7 in hidden textbox
plz any one help me.
Autocomplete textbox
<input id="society_name" name="society"/>
<input type="hidden" id="society_name" name="societyid"/>
In ajax.php
if($_GET['type'] == 'society'){
$result = mysql_query("SELECT society FROM societymaster where society LIKE '".strtoupper($_GET['name_startsWith'])."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row['society']);
}
echo json_encode($data);
}
auto.js
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
Use the val() function on the input pass the id from the ajax results
$('#society_name').val(data.id);
Updated code:
php:
if($_GET['type'] == 'society'){
$result = mysql_query("SELECT id,society FROM societymaster where society LIKE '".strtoupper($_GET['name_startsWith'])."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data,$row);
}
echo json_encode($data);
}
js:
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
$('#society_name').val(data[0].id);
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
If you need IDs then fetch them from DB and return in ajax call (I guess this is the ID you are talking about).
From this point you can use something like this, that you cache the returned results in e.g. associative array:
$arr[value] = id;
and if user selects one of the values you can get the corresponding ID.
That's one method I guess.
BTW.
some tips for the future:
1. The id's fields should have unique values.
2. You should consider protecting your query from sql attacks. Here you do not even escape the string which is given by the user.
3. As far as I remember the mysql is obsolete so try to use mysqli instead.
ajax.php
if($_GET['type'] == 'society'){
// try to switch to mysqli. You can also consider prepare statements.
$result = mysql_query("SELECT id, society FROM societymaster where society LIKE '".mysql_real_escape_string(strtoupper($_GET['name_startsWith']))."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
// mysql_fetch_array returns indexed array so we should get JSON string like: "[['id1', 'value1'], ['id2', 'value2'], ...]"
echo json_encode($data);
}
.js file
$.arr = [];
$('#society_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'society'
},
success: function( data ) {
// clear cache array and fill it with information about the new results (societies and corresponding ids)
$.arr = [];
$.each(data, function (idx, item) {
$.arr[item[1]] = item[0];
});
$('#society_name').val(data[0].id);
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
// catch an event when the autocomplete closes and get id for selected society name
$("#tags").on("autocompleteclose", function() {
// close event does not provide object data so we must fetch it again
var selectedValue = $("#tags").val();
var id = $.arr[selectedValue];
// now you can set this ID as the value of your hidden input
});
I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys
function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));
I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};
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");
}
});