0

here's my code. I'm new to php. so sorry in advance. I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?

        <?php
            $barcode = $_POST['txtbarcode'];
            $query = "SELECT * FROM product WHERE product_id = '$barcode'";
            $query_exe = mysql_query($query);
            $chk_query = mysql_num_rows($query_exe);

            if($chk_query > 0)
            {
            $row = mysql_fetch_assoc($query_exe);

            ?>
            <th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>"  style="width:80px"/></th>
            <th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>"    style="width:100px"/></th>
            <?php
            }
            ?>
Sam Teng Wong
  • 2,379
  • 5
  • 34
  • 56

1 Answers1

2

You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).

The following is a separate PHP file.

<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------

if (isset($_POST['barcode'])) {
    $query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
    $num_rows = mysql_num_rows($query);
    if ($num_rows > 0) {
        $row = mysql_fetch_assoc($query);
        echo $row['product_name'];
    }
}
?>

The following is your HTML and JavaScript code.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>
    $(document).ready(function() {
        $('#txtbarcode').change(function() {
            var barcode = $(this).val();
            $.ajax({
                url: 'check_barcode.php',
                type: 'POST',
                data: {barcode: barcode},
                success: function(result) {
                    $('#txtdescription').val(result);
                }
            });
        });
    });
</script>

<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />


UPDATE: Returning more data, and populating extra fields.

You'll need you echo a json array from the php script which contains both of the values.

For example:

echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));

and then within the JavaScript

<script>
$.ajax({
    url: 'check_barcode.php',
    type: 'POST',
    data: {barcode: barcode},
    dataType: 'json',
    success: function(result) {
        $('#txtdescription').val(result.product_name);
        $('#unitofmeasure').val(result.unit_measure);
    }
});
</script>
weiver
  • 226
  • 2
  • 3