populate input hidden with the id of a value from autocomplete.js - php

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);
},
});
});

Related

how to convert multiple array to string in php

Hi All,
i'm getting all the data from database for array format i need to pass that data to second drop down list like (group option value),please any one help me.
This is my php code:
<?php
//error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$db = "essae";
$data = "";
$subcategory_id = "";
$subcategory_name = array();
$conn = mysqli_connect($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category= $_GET["category_id"];
$sql = "SELECT es_category.category_id,es_category_description.name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$result = $conn->query($sql);
if ($result->num_rows > 1){
$sql_getrec ="SELECT es_category.category_id AS sub_cat_id,es_category_description.name AS sub_cat_name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$sub_category= $conn->query($sql_getrec);
if ($sub_category->num_rows > 1){
while ($row=mysqli_fetch_array($sub_category)){
$subcategory_id = $row['sub_cat_id'];
//$subcategory_name['sub_category_name'][] = $row['sub_cat_name'];
$sql_getrec = "SELECT es_product_description.name AS prod_name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id = $subcategory_id AND es_product.status=1";
$sub_product=$conn->query($sql_getrec);
while ($prow=mysqli_fetch_array($sub_product)){
$subcategory_name['sub_category_name'][$row['sub_cat_name']]['products_name'][] = $prow['prod_name'];
}
}
echo "<pre>";print_r($subcategory_name);
}
}
else {
$sql_getrec = "SELECT es_product_description.name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id='$category' AND es_product.status=1";
$result_getrec=$conn->query($sql_getrec);
while ($row=mysqli_fetch_array($result_getrec)){
$data .= $row['name'].",";
}
$data = rtrim($data,",");
}
print_r($data);
?>
This is my Html code:
<php?
$decocedData1 = json_decode($str_json_format, TRUE);
//print_r($decocedData1);die;
$decode = $decocedData1;
?>
<div>
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
</div>
<div><select name="category12" id="category12" />
</select>
</div>
this is my j query and ajax method code:
<script type="text/javascript">
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
});
$('#category12').html(state_html);
},
});
})
});
</script>
You may use Type Casting in php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
<?php
$array = array("name", "age", "mobile", "email");
var_dump($array);
(string)$array;
var_dump($array);
?>
This is not your final answer but you can try below code and figure out your variable names
$('#category12').empty();
$.each(data, function (index) {
var optgroup = $('<optgroup>');
optgroup.attr('label',data[index].name);
$.each(data[index].children, function (i) {
var option = $("<option></option>");
option.val(i);
option.text(data[index].children[i]);
optgroup.append(option);
});
$("#category12").append(optgroup);
});
$("#category12").multiselect('refresh');
you can do a jquery each in the result of your ajax
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
$(function(){
//sample result, this will be your ajax result....
var products = ["Candy", "Cotton Candy", "Iced Candy"];
//clear again the select element.
$('#category12').empty();
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category12"></select>

Get ID and Name Autocomplete JQuery PHP

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

Autocomplete show an undefined list

I've been working with jQuery UI Autocomplete to make an suggestion from database and autocomplete the rest of field.
Here is my code.
HTML :
<form action="#" method="post">
<p><label for="kdbr">KDBR</label><br />
<input type="text" name="kdbr" id="kdbr" value="" /></p>
<p><label for="nmbr">NMBR</label><br />
<input type="text" name="nmbr" id="nmbr" value="" /></p>
</form>
Javascript :
$(function() {
//clear values on refresh
$('#nmbr').val("");
$("#kdbr").autocomplete({
source: "<?php echo base_url();?>js/coba3.php",
minLength: 3,
select: function(event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
});
PHP :
<?php
$dbhost = 'HOST';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'TBNAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM tb_master_barang where kdbr like '%" .mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['kdbr'] = htmlentities(stripslashes($row['kdbr']));
$row_array['nmbr'] = $row['nmbr'];
array_push($return_arr,$row_array);
}
}
mysql_close($conn);
echo json_encode($return_arr);
?>
The dropdown list show a list of undefined instead value from kdbr . I have run the php separately and it returns this value :
[{"kdbr":"950.00.0002","nmbr":"PAKAIAN DINAS KS"},{"kdbr":"950.01.0000","nmbr":"BARANG SCURITY LSNG.PAKAI"},{"kdbr":"950.01.0001","nmbr":"PECI"},{"kdbr":"950.01.0002","nmbr":"KOPEL REM HITAM"},{"kdbr":"950.01.0003","nmbr":"SEPATU PDH"},{"kdbr":"950.01.0005","nmbr":"ROMPI SATPAM"},{"kdbr":"950.01.0006","nmbr":"SEPATU PDL"},{"kdbr":"950.01.0007","nmbr":"TALI KOOR & PLUIT"},{"kdbr":"950.01.0008","nmbr":"PAKAIAN TAHAN API"},{"kdbr":"950.01.0009","nmbr":"HELM TAHAN API"},{"kdbr":"950.02.0001","nmbr":"KAOS SCURITI PNJG\/BED\/LOG DLL"}]
can someone tell me where i doing wrong?
Your source field is used in a wrong manner. You need to pass array with data or a anonymous function which will load the data. See the documentation
Something like this should work:
$("#kdbr").autocomplete({
source: function (request, {
var ajax_url = "<?php echo base_url();?>js/coba3.php?term=" + request.term;
$.ajax({
url: ajax_url,
success: function (response) {
// assuming valid json
var data = $.parseJSON(response);
response($.map(data, function (obj) {
return {
label: obj.name + ': ' + obj.description,
value: obj.name,
id: obj.name
};
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
try this,
select: function(event, ui) {
jQuery.get(ui.item.nmbr);
}

Auto complete base on value of dropdown in database

I'm stuck with this problem with in a week. What I have here is dropdown select with ajax posting value to another dropdown but now I need to post into textbox with autocomplete function. What I need is connect my autocomplete query and my ajax so that if I select for example ballpen, all ballpen will recommend in autocomplete. Please Help me with this. I need to finish it.
Here's my code
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
In here I post the value in another dropdown but not I need to post into textbox.
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
autocomplete.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
//whenever u select the tag field will get focus, and it automatically start searching so u no need to type see the callback focus function with $(this).autocomplete("search", ""); and minlength 0. u have to send the main value and get the response from here too
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
untested, if any question post comment

AJAX PHP- Loads the previous inserted record instead of first

I have a raw commenting system where one can post comments. When the post button is clicked, an AJAX request is sent to the php file (process.php). In process.php, there's a while loop which retrieves all the comments and sends back to the index.php file as data.
Problem is When I post two comments, the comment which I posted before the current one is shown in the div specified!
index.php
if(isset($_POST['text'])){
if(!empty($_POST['text'])){
$text = $_POST['text'];
$query = mysql_query("INSERT INTO `test` VALUES('', '$text')");
}
}
?>
<form action="" class="comment_post" method="POST">
<input type="text" name="text">
<input type="submit" value="POST">
</form>
<hr>
<div id="comments">
</div>
<script>
$('form.comment_post').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value= that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data
});
return false;
});
$('input[type=submit]').click(function(){
$.ajax({
type : 'POST',
url : 'process.php',
data : {action: 'retrieve'},
success : function(data){
$('#comments').html(data);
}
});
});
</script>
process.php
if(isset($_POST['action']) && !empty($_POST['action'])){
$action = $_POST['action'];
if($action == 'retrieve'){
$data = mysql_query("SELECT * FROM `test`");
if(mysql_num_rows($data) != 0){
while($row = mysql_fetch_assoc($data)){
$text = $row['text'];
echo '<div class="each_comment">'.$text.'</div><br>';
}
} else {
echo 'No data to retrieve';
}
}
}
?>
first extend your database by a column "dateCreated"
then use this insert code:
$query = mysql_query("INSERT INTO `test`,`dateCreated` VALUES('', '$text','NOW()')");
in your process.php use the code like this:
$data = mysql_query("SELECT * FROM `test` ORDER BY `dateCreated` DESC ");

Categories