'Get database value based on another input field
I've been searching for this kind of problem and I couldn't find one. I am using ajax to solve this problem but it didn't work out. I really want to have this scenario where after the user scanned his/her QR code, its data (account ID) will be in the input field. Then the other input field will automatically show its corresponding data from the database based on the data from QR code. This is so far my code.
This is from the main page:
<label id="acc">Account ID
<input type="text" name="accId" id="accID" class="idnum" required="" value="">
</label>
<label id="label">QR ID
<input type="text" readonly=" " name="qrId" id="qrId" style="width: 108px;margin-right: 15px;" value="" >
</label>
Ajax:
<script>
$("#accID").change(function() {
var accID = $(this).val();
$.ajax({
url: 'loadata.php',
type: 'POST',
data: 'accID='+accID,
success: function(html) {
$("#qrId").html(html);
}
});
});
</script>
this is the loadata.php:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
while($rows = $sel_run->fetch_assoc())
{
?>
<input type="text" readonly=" "id="qrId" name="qrId" style="width: 108px;margin-right: 15px;" value="" >
<?php
}
}
}
?>
Thank you very much for your time! :)
Solution 1:[1]
Are you getting any data to return? Have you tried changing your input field in loadata.php to a div with the same ID? Right now you're trying to place an input within an input.
Also, you don't need to wrap your inputs within the label. As long as the label and input share the same ID, they will always be together. Currently, you are not doing that.
Solution 2:[2]
Setting $("#qrId").html(html);
will do nothing, as #qrId
is an input field. I think, what you want to do is to set the value
of the input field.
This should work like this: $("#qrId").val(html);
Then, there is a second problem as your PHP script returns HTML of an input field rather than just the value to set. Also, it may return multiple values as you loop through the database results.
You could try to change your script to something like this to just return the value of the first selected database record. Replace qrCodeValue
with the real column name to use:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
$row = $sel_run->fetch_assoc();
print $row['qrCodeValue'];
exit;
}
}
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jaypat32 |
Solution 2 | t.h3ads |