Autocomplete show an undefined list - php

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

Related

Check if value is exist in database jQuery and php

I m having a bit of trouble while validating value in database.
This is my html and js Code:
<input type="text" name="Unieke-voucher" value="" size="40" maxlength="8" minlength="8" id="voucher" aria-required="true" aria-invalid="false" placeholder="XYZ 1234">
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(vCode) {
jQuery.ajax({
url: 'voucher.php',
type: 'GET',
dataType: 'json',
data: {value: vCode},
success: function(data) {
if(data.status) {
jQuery("#codeError").html('');
console.log(data);
} else {
jQuery("#codeError").html('Value not found');
}
console.log(data);
}
});
}
With this getting value with keyup event and sending to php script till here working fine.
And this is php script:
$dbname = "voucher";
$dbuser = "root";
$dbpass = "root";
$dbhost = "localhost";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$voucherCode = $_GET['VoucherCode'];
$voucherCode['status'] = false;
//echo $voucherCode;
$result = mysqli_query($conn, "SELECT * FROM VoucherCode WHERE `code` LIKE '$voucherCode' LIMIT 1");
if(mysqli_num_rows($result)) {
$userData = mysqli_fetch_assoc($result);
$voucherCode['code'] = $Code;
$voucherCode['status'] = true;
}
echo json_encode($voucherCode);
I am always getting status value even providing correct value.
When i print_r table like
$resultAll = mysqli_query($conn, "SELECT * FROM VoucherCode");
$data2 = mysqli_fetch_all($resultAll);
print_r($data2);
I am able to see all data is there.
I am not sure what i am doing wrong here. Can anyone help me with this please.
Thanks in advance.

Send SQL concat to PHP variable

I am trying to select multiple columns with concat an put the returned data into one textbox.
I think there is something wrong with my definition for the variables. But I could not figured out what is wrong. Here are the variables:
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
When I define just one variable for $name the script works. But that is not what I want.
Does someone know what is wrong?
Here is the other part of my script.
First I have a textbox. The data needs to be send to this textbox:
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
The button calls sends '5' as the ID and runs the script getName():
<button type="button" rel="5" onclick="getName();"
<script type="text/javascript">
$('body').on('click', '.selectClass', function () {
var id = $(this).attr('rel');
$("#id").val(id);
modal.style.display = "none";
});
</script>
After clicking on the button the id is deployed here:
<input type="text" class="form-control" id="id" name="id">
The onClick event runs the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getName(value) { // Do an Ajax request to retrieve the product price
console.log("getName before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/getname5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getName after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The jquery script calls the PHP, which is not working with the multiple variables for $name
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id'])?$_POST['id']:'';
$name = isset($_POST['firstname'])?$_POST['firstname']:'';
$name .= isset($_POST['insertion'])?$_POST['insertion']:'';
$name .= isset($_POST['lastname'])?$_POST['lastname']:'';
$query = 'SELECT concat(firstname, ' ', insertion, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>

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

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

submitting form from jquery to php

I'm going crazy! I'm trying to submit a form from jquery to php and insert a record in my database. I'm getting no error, but no record is being submitted. All works fine when I just go to the php page and put variables in the URL. But it doesn't work when I submit the variables via the jquery page. Can anyone help me out, please?
HTML:
<form id="tellusForm" >
<div class="formHead">Tell us your story</div>
<div id="thank">Thank you.</div>
<table cellpadding="5">
<tr><td>Name:</td><td><input id="tellName" type="text"/></td></tr>
<tr><td>Country of origin:</td><td><select id="tellCountry"></select></td></tr>
<tr><td>Age:</td><td><input type="text" id="tellAge"/></td></tr>
<tr><td>Occupation:</td><td><input type="text" id="tellOccupation"/></td></tr>
<tr><td>Email address:</td><td><input type="text" id="tellEmail"/></td></tr>
<tr><td>Phone number:</td><td><input type="text" id="tellPhone"/></td></tr>
<tr><td>A bit about you:</td><td><textarea id="tellAbout" style="width: 100%;"></textarea></td></tr>
<tr><td></td><td><input type="submit" value="Send" class="submit"/></td></tr>
</table>
</form>
jquery:
$('.submit').click(function(){
$.get('tellus.php', { name: "laura"}, function(data){
eval(data);
});
});
tellus.php:
<?php
require_once ('../constants_test.php');
$name = $_GET['name'];
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
$q = "Insert into tellus(`Name`) values ('" . $name . "')";
if ($db->query($q)) {
echo "console.log('you got it')";
};
$db->close();
?>
Thanks everyone who tried to help me! I ended up having to do it this way:
$.post("./tellus.php", {tellName:name}, function(data){
alert(data)
});
The ajax call must have had something that wasn't working.
Use serialize():
$("#tellusForm").on("submit", function() {
event.preventDefault();
$.ajax({
url: 'tellus.php',
data: $(this).serialize()
}).done(function(data) {
$(html).append(data);
});
});
Also make sure to have names on your form elements:
<input type="text" name="tellAge" id="tellAge" />
This topic is very common here so try searching for other posts - e.g. Submit form using AJAX and jQuery could work too.
The ajax call wasn't working because you are using $.serialize to serialize your form objects, which will return ;
{key:'tellName', value='name'} // <input name="tellName" value="name" />
whereas you are expecting a key:value pair. In order to get the data to send what you expecting, you should modify the object using this jQuery function:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}
And call it whenever you're submitting form. It will structure your form to have the key:value pair.
<form id="register">
<input type="text name="username" />
<input type="text" name="email" />
<input type="submit value="Register!" />
</form>
and the javascript (remember to include the serializeObject function)
$('#register').on('submit', function(){
var data = $(this).serializeObject()
// data will return {username: value, email:value}
$.post('process.php', data, function(response){
try{
var r = JSON.parse(response) // Check if the response is an object
console.log(JSON.stringify(r))
}
catch(e){
console.log(response) // The response is a string
}
})
})
Cheers!
I suggest you should use POST for actions which include insert/delete/update of data in database. It keeps the data safe.
If you want to still use GET and test out something. I suggest do not use jquery in the middle to handle the get. Submit button on click submits the form anyway, so the jquery $.get is unnecessary.
To your form element add
<form name='' action='tellus.php'>...</form>
This should fix the problem.
How about this one
jquery
$("#submit").click(function() {
formData = {
name: "abc"
}
$.ajax({
type: 'GET',
contentType: 'application/json',
url: "http://yourpage/tellus.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data.message);
},
error: function(data) {
console.log(data.message);
}
});
});
php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_GET['name'])) {
$name = $_GET['name'];
// include db connect class
require_once ('../constants_test.php');
// connecting to db
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
// mysqli inserting a new row
$q = "INSERT INTO tellus('Name') values ('" . $name . "')";
// check if row inserted or not
if ($db->query($q)) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "you got it";
// echoing JSON response
echo json_encode($response);
$db->close();
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
$db->close();
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

jQuery code causing conflict in results

I would like to ask, is there a better way to run this code. I have a form with a select of #BA_customer which when selected populates a second menu with the address of the selected client. I also need to display a dept dropdown based on the customer selecetion. I think the code I have is causing a conflict where the customer is being passed twice in 2 seperate statements. What is the correct way to do this? Many thanks
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data); });
});
});
</script>
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data); });
});
});
</script>
+++++++ dept.php Code +++++++++++++++++++++
$customer = mysql_real_escape_string( $_GET["BA_customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_select_dept = mysql_query($query_rs_select_dept, $con) or die(mysql_error());
$row_rs_select_dept = mysql_fetch_assoc($rs_select_dept);
$totalRows_rs_select_dept = mysql_num_rows($rs_select_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_select_dept = mysql_fetch_assoc($rs_select_dept))
{
$dept=$row_rs_select_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
++++ SOLUTION +++++++++++++
mysql_select_db($db, $con);
$query_rs_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_dept = mysql_query($query_rs_dept, $con) or die(mysql_error());
$totalRows_rs_dept = mysql_num_rows($rs_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_dept = mysql_fetch_assoc($rs_dept))
{
$dept=$row_rs_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
Remove the first $row_rs_select_dept = mysql_fetch_assoc($rs_select_dept); from the script and it works. Just posted solution in case some other soul needs help with problem like this.
Maybe you could send the two requests together?
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data);
});
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data);
});
});
});

Categories