So, I have this jquery code in my php page that gets data from a mysql table:
$(function() {
$("#tracking_num").autocomplete({
source: "func/populate.php",
minLength: 2,
select: function(event, ui) {
$('#name').val(ui.item.name);
$('#particulars').val(ui.item.particulars);
$('#remarks').val(ui.item.remarks);
$('#location').val(ui.item.location);
}
});
});
I'm challenged to get the data immediately into the fields without selecting it from the drop down box. Do you guys have any idea how to do it? Here's my the func/populate.php file:
$return_arr = array();
$fetch = mysql_query("SELECT * FROM tbl_document WHERE tracking_number = '" . mysql_real_escape_string($_GET['term']) . "' ORDER BY id DESC LIMIT 1");
while ($row = mysql_fetch_array($fetch) ) {
$row_array['name'] = $row['name'];
$row_array['particulars'] = $row['particulars'];
$row_array['remarks'] = $row['remarks'];
$row_array['location'] = $row['location'];
$row_array['value'] = $row['tracking_number'];
array_push($return_arr,$row_array);
}
mysql_close();
echo json_encode($return_arr);
Have you tried :
$(function() {
$("#tracking_num").autocomplete({
source: "func/populate.php",
minLength: 2,
create: function(event, ui) {
$('#name').val(ui.item.name);
$('#particulars').val(ui.item.particulars);
$('#remarks').val(ui.item.remarks);
$('#location').val(ui.item.location);
}
});
});
?
Related
I am trying to work out why my alert in the 'function processResponse(data)' part of the code, is not being displayed. I have tried various return; options, but still, refuses to display.
I would be grateful if someone could point out my error. Many thanks.
PS. I am aware of security issues in the code posted such as mysql_escape_string, but all security issues will be inserted before the site goes live.
jQuery code
<script type="text/javascript">
$(function() {
$('#srcsubmit').click(function(e) {
e.preventDefault();
if ($('#srcBox').val() == '') {
notif({
type: "error",
msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click anywhere to close</p>",
height: 99,
multiline: true,
position: "middle,center",
fade: true,
timeout: 3000
});
return false;
}
$("#submit").prop("disabled", true);
$("#submit2").prop("disabled", true);
$("#submit3").prop("disabled", true);
var value = $('#srcBox').val();
var dept = '<?php echo $_GET['dept ']; ?>';
var qString = 'sub=' + encodeURIComponent(value) + '&dept=' + encodeURIComponent(dept);
$.post('sub_db_handler.php', qString, processResponse);
});
function processResponse(data) {
if (data === 'true') {
alert('That box is not on the system'); <--- this is the problem
return;
}
$('#srcBoxRslt').val(data);
};
});
</script>
PHP backend
<?php session_start(); ?>
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("sample", $con);
$dept = trim($_POST['dept']);
$custref = trim($_POST['sub']);
$result = mysql_query("SELECT * FROM boxes WHERE custref = '".$custref."'");
$found = mysql_num_rows($result);
if ($found == 0)
{
echo trim('true');
} else {
$query = "SELECT * FROM boxes WHERE department = '".$dept."' AND status = 1 AND custref = '".$custref."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$r = $row['custref'];
$str = json_encode($r);
echo trim($str, '"');
}
?>
The data value is not equal to true because of extra space to get rid of extra use .trim()
I have problem with autocomplete in Codeigninter and Jquery
I have a controller
<?php
public function search() {
$user = $_GET['term'];
$query = $this
->db
->select('nama_kota')
->like('nama_kota', $user)
->get('kota');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row_set[] = htmlentities(stripslashes($row['nama_kota']));
}
echo json_encode($row_set);
}
}
?>
I have a view
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
$("#user-input").autocomplete({
source: availableTags
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
everything its okay
but I'm trying multiple values
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#user-input").autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
no work and availableTags only read addres url no function in controller
whats wrong guys please help me, Thanks
which type off output you need If you need like this
eg.
name,
address,
blood_group.
with output of Autocomplete call
Sorry For late reply I am very very busy in my work
this is JS call to Controller
<script>
jQuery("#h_student_name").autocomplete({
minLength: 0,
source: "DropdownController/hostel_students/" + $("#h_student_name").val(),
autoFocus: true,
scroll: true,
dataType: 'jsonp',
select: function (event, ui) {
jQuery("#h_student_name").val(ui.item.contactPerson);
jQuery("#h_student_id").val(ui.item.code);
}
}).focus(function () {
jQuery(this).autocomplete("search", "");
});
</script>
and this is controller for call
<?php
//Hostel Student Auto compelete
public function hostel_students(){
$term = trim(strip_tags($this->input->get('term')));
if( $term == ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1));
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
} else if($term != ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1), $like);
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
}
}
?>
and this is model for call
<?php
// Hostel student autocomplete
public function hostel_students($where, $like = NULL){
if($like):
$this->db->like('student_name', $like);
$this->db->or_like('form_no', $like);
$this->db->or_like('college_no', $like);
endif;
$this->db->join('student_record', 'student_record.student_id=hostel_student_record.student_id');
return $this->db->where($where)->get('hostel_student_record')->result();
}
}
?>
have any issue comment me I will online today
I'm using this function to get autocomplete on input value
<input type="text" id="product_name">
$( '#product_name' ).autocomplete({
source:'autocomplete.php',
minLength:2,
select: function(event,ui){
$('#product_name').val( ui.item.name );
}
});
but the line
$('#product_name').val( ui.item.name );
doesn't work...
From php I store in json, "value" that is product name with different attribute, and in "name", ONLY the product name
Then, when I search with 2 digits, the results are like
product1 - qt:0 - price:20
product2 - qt:4 - price:7
product3 - qt:3 - price:11
and when I select I want to update my input only with name that is stored in ui.item.name
This is my autocomplete.php
$sql = "SELECT name, CONCAT (quantity,' - ',name,' - ',price) AS value
FROM `product` ";
$res= $db->query($sql);
while ($r = $res->fetch()) {
$a_json_row["name"] = r['name'];
$a_json_row["value"] = $r['value'];
array_push($a_json, $a_json_row );
}
echo json_encode($a_json);
flush();
Json returned from autocomplete.php is:
[{
"name": "MOCCOLO 60X165",
"value": "[12] - MOCCOLO 60X165 : 4.00"
}, {
"name": "MOCCOLO 80X150",
"value": "[19] - MOCCOLO 80X150 : 6.50"
}, {
"name": "MOCCOLO 80X200",
"value": "[69] - MOCCOLO 80X200 : 8.00"
}]
This is when I search
This is when I select
But I want
First, your php was at fault. Your ide/editor should have warned of such a simple mistake. You need to invest on better tools..
$sql = "SELECT name, CONCAT (quantity,' - ',name,' - ',price) AS value
FROM `product` ";
$a_json = [];
$res = $db->query($sql);
while ($r = $res->fetch()) {
$a_json[] = [
"name" => $r['name'],
"value" => $r['value']
];
}
header('Content-type: application/json');
echo json_encode($a_json);
flush();
Then, your JS should be like this:
$('#product_name').autocomplete({
source: "autocomplete.php",
minLength: 2,
select: function(event, ui) {
$('#product_name').val(ui.item['name']);
return false;
}
});
Working example.
I've been struggling with this code for a while and honestly I'm stuck.
This is how my auto-complete script looks like:
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
source:'adress.php',
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
Some more js to get me the additional value:
<script type='text/javascript'>
$('#city').on( 'change', function () {
var x = document.getElementById('city').value;
$.ajax({
type: 'post',
url: 'http://localhost/profsonstage/account/_compettions/autocomplate/location_name.php',
data: {
value: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>*/
And the php that fetches the data results:
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
The problem is when the user types a value in the input for the #City the query looks like this:
$query = "SELECT * from locations where adress like '%%' and
city=='SomeCity'
LIMIT 0 , 5";
and when we go to the next input that (is supposed to be autocomplete too and start typing) the query looks like
$query = "SELECT * from locations where adress like '%input to autocomplate%' and
city==''
LIMIT 0 , 5";
Basically I can't figure out a way to pass the values at the same time. Any help will be appreciated.
You can use following;
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
source: function( request, response ) {
var term = request.term;
$.getJSON( "address.php?term=" + term + "&city=" + $("#city").val(), request, function( data, status, xhr ) {
response( data );
});
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
And in your php file;
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
//Fetch your data and respond json
I have input with id aktForm_tiekejas and is jquery autocomplete code:
$('#aktForm_tiekejas').autocomplete({
serviceUrl: '_tiekejas.php',
width: 185,
deferRequestBy: 0,
noCache: true,
onSelect: function(suggestion) {alert('You selected:'+suggestion.value+','+suggestion.data);}
});
_tiekejas.php:
<?php
include("../Setup.php");
$query = ($_GET['query']);
$reply = array();
$reply['query'] = $query;
$reply['suggestions'] = array();
$reply['data'] = array();
$res = mysql_query("SELECT id,pavadinimas FROM sarasas_tiekejas WHERE pavadinimas LIKE '%$query%' ORDER BY pavadinimas ASC");
while ($row = mysql_fetch_array($res)) {
$reply['suggestions'][] = $row['pavadinimas'];
$reply['data'][] = $row['id'];
}
mysql_close();
echo json_encode($reply);
?>
If query is 'vac' php returns from server:
{"query":"vac","suggestions":["UAB Vivacitas"],"data":["866"]}
but
alert('You selected:'+suggestion.value+','+suggestion.data);
doesn't alert data (866)
why?...
Probably because suggestion.value doesn't exist. Looking at your JSON response code I can see the suggestion.data but no suggestion.value. Since JS will be looking for a value that doesn't exist it will throw an error. Also you're missing out the array for the second part of the return. Try this:
alert('You selected: '+suggestion.data[0]);
If you need to iterate through your data subsets do something like:
for(i in suggestion.data){
alert('You selected: '+suggestion.data[i]);
}