I can`t find the way to get the ID of my element when you search in the autocomplete textbox: I have this in mi HTML:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#local" ).autocomplete({
source: 'buscar_local_nombre.php'
});
});
And this is "buscar_local_nombre.php":
<?php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'restofinder';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $db->query("SELECT * FROM locales WHERE NOMBRE LIKE '%".$searchTerm."%' AND ESTADO = 1 ORDER BY NOMBRE ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['NOMBRE'];
}
//return json data
echo json_encode($data);
?>
How could I get ID too (hidden) so that i can store it in a variable and use it afterwards?
Thank you very much!
Use select
$(function() {
$( "#local" ).autocomplete({
source: 'buscar_local_nombre.php',
select: function (event, ui) {
$("#hdnId").val(ui.item.id);//Put Id in a hidden field
}
});
});
Reference
Autocomplete get id as selected label
jQuery Autocomplete
Autocomplete select name and display id
Related
What i have working at the moment is the autocomplete when i type the name of a person.. what i need is when i select the name automatically fill a hidden field with the id from that person.
my codes:
<form action="cadastroAdm.php" method="post" name="clientForm">
<input type="text" name="clienteId" id="clienteId">
<input type="text" name="clienteNome" id="clientes">
</form>
jquery
$(document).ready(function() {
// Captura o retorno do retornaCliente.php
$.getJSON('php/retornar_cliente.php', function(data){
var dados = [];
// Armazena na array capturando somente o nome do EC
$(data).each(function(key, value) {
dados.push(value.clienteNome);
});
$('#clientes').autocomplete({
source: dados,
minLength: 3,
select: function(event, ui) {
$('#clienteId').val(ui.item.id);
console.log(ui.item.id);
},
});
});
});
retornar_cliente.php
<?php
$hostname = "";
$user = "";
$pass = "";
$basedados = "";
$pdo = new PDO("mysql:host=localhost; dbname=adv; charset=utf8;",'root','');
$dados = $pdo->prepare("SELECT clienteNome, clienteId FROM cliente ORDER BY clienteNome");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));
?>
in the console log i just receive "undefined"..
what i m doing wrong?
Just change your query with this :
"SELECT clienteNome, clienteId as id FROM cliente ORDER BY clienteNome"
Or change your variable in JS with this :
ui.item.clienteId
Edit :
You didn't push id in your dados array.
Please refer this link : http://jqueryui.com/autocomplete/#remote
problem solved.. follow the code i used:
retornar_cliente.php
<?php require_once("conexao/conexao.php"); ?>
<?php
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT clienteNome as value,clienteId as id FROM cliente WHERE clienteNome LIKE '%".$term."%'";
$consulta_tr = mysqli_query($conecta, $qstring);
if(!$consulta_tr) {
die("erro no banco1");
}
while ($row = mysqli_fetch_array($consulta_tr,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
html
<form action="cadastroAdm.php" method="post" name="clientForm">
<input type="text" name="clienteId" id="clienteId">
<input type="text" name="clienteNome" id="clientes">
</form>
jquery
$(document).ready(function() {
$('#clientes').autocomplete({
source: 'php/retornar_cliente.php',
minLength: 3,
select: function(event, ui) {
$('#clienteId').val(ui.item.id);
},
});
});
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});
I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.
So I created an auto complete box using jQuery and PHP to pull the content from the database, and it's working fine, except when I go to type in the input box it pulls back all the results, instead of the results similar to what I'm typing.
So if you type Test it pulls back:
This
is
a
Test
Instead of displaying
Test
Here is my HTML
<input type="text" id="group_name" name="group_name">
Here is the jQuery I'm using
<script>
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream/group_names",
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
Here is my php page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
Recent Updates
New jQuery
<script>
var availableName;
$.getJson('/wuzhapnn/php/data_stream',function(response){
availableName = response;
});
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: availableName,
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
New PHP Page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
You need to add LIKE clause.
"SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
because "SELECT group_name FROM groups" this will give all the result from database but you need only those who match with typed words so use LIKE MySQL clause.
Other Person Comment Response.
if you want to create json object before use it you can do it as below,
var availableName;
$.getJson('/wuzhapnn/php/data_stream/group_names',function(response){
availableName = response;
});
after this just use below code for autoComplete.
$( "#group_name" ).autocomplete({
source: availableName ,
Your PHP snippet doesn't actually use the value sent by the autocomplete plugin.
If you are using JQuery's plugin then the value send is a GET parameter called terms.
This needs to be included in your PHP.
$term = $_GET['term'];
You then need to include that in your query something like the following, but first please escape this value before using it directly in an SQL statement.
SELECT group_name FROM groups WHERE group_name LIKE %<term>%
Got it working right
New jQuery
<script>
$(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream",
minLength: 2,
});
});
</script>
New PHP (thanks to Dipesh Parmar)
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
echo json_encode(array_values(array_unique($group_names_array)));
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});