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.
Related
i am doing my school project. I manage to add/delete in database from my data-table checkbox if the value is check then it will add then if uncheck then it will be deleted, Now what i want is , when i go load the data table with checkbox, i want to check already the values that is already in my database. For example, if i have user_id = 102 already in my database, if i load the data-table, i want the name with user_id value of 102 will be automatically check when fetching the data-table checkbox. How can i do it? i am using a codeigniter framework.
Here is my controller in populating my data-table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is my ajax/javascript:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
and then i put the function into document-ready:
$(document).ready(function() {
$('#dataTables-docs').dataTable();
show_docs();
});
what i want is when i will go load my data-table, i want to check all the data-table checkbox if it is already in the database.
You're just comparing arrays. I'm not PHP coder, so what follows might be a poor method, but it demonstrates the principle of comparing one array with another. Actually, it compares an array with an interating value, but that iterating value could just as easily be borrowed from another array...
<?php
$my_array = array(
0 => 1,
1 => 2,
2 => 3,
3 => 5,
4 => 7
);
for($i=0;$i<10;$i++){
echo $i;
if(in_array($i,$my_array)){echo " yes <br>\n";} else {echo " no <br>\n";}
}
?>
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);
}
});
});
?
I have a jquery script that works with a city search field
Script
<script type="text/javascript">
$(document).ready(function()
{
var ac_config =
{
source: "demo_cities.php",
select: function(event, ui)
{
$("#City").val(ui.item.City);
$("#Country").val(ui.item.Country);
$("#DestinationId").val(ui.item.DestinationId);
},
minLength:3
};
$("#City" ).autocomplete(ac_config);
});
</script>
and php code is
<?php
$cities= array(
array('City'=>'Barcelona',
Country=>'SP',
DestinationId=>'10001'),
....... );
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $City)
{
if(stripos($City['City'], $term) !== false)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
How can i make the script to search only by the first 3 charachers from the City name
In your PHP code, you're looking for a city that contains a string in city name. If you want to show cities that starts with specific chars, you could use substr
<?php
$cities= array(
array('City'=>'Barcelona',
'Country'=>'SP',
'DestinationId'=>'10001'
),
//more cities ...
);
$term = strtolower(trim(strip_tags($_GET['term'])));
$matches = array();
foreach($cities as $City)
{
if(strtolower(substr($city['city'], 0, strlen($term))) == $term)
{
$City['value'] = $City['City'];
$City['label'] = "{$City['City']}";
$matches[] = $City;
}
}
$matches = array_slice($matches, 1, 7);
print json_encode($matches);
?>
normally city will not change its name, so I put city name in a js file, then let FE to do search,
and autocomplete part seems no question.
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]);
}