简体   繁体   中英

Jquery autocomplete two fields based on one field using PHP and MySQL

I have a table in MySQL database with following columns: name, address, occupation, phone_number and serial_number. In my html form, among other fields, I have text fields for inputting Name, Phone number and Serial number. How can I, using jQuery autocomplete and PHP/MySQL populate the Name and Phone number fields using the Serial number field? I've managed to set autopopulate on one input field, but I don't know how to set it to populate the other two fields using the one field which has autocomplete. Thanks

these are the fields

   <input type="text" name="name" id="autocomplete" />
   <input type="text" name="phone_number" id="autocomplete" />
   <input type="text" name="serial_number" id="autocomplete" />

this is my php script for getting the strings from db

<?php
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

$return_arr = array();

if ($conn)
{
    $fetch = mysql_query("SELECT name, phone_number, serial_number FROM users");


    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
        $row_array['value'] = $row['name'] . " " . $row['phone_number'] " . $row['serial_number'] ";         
        array_push($return_arr,$row_array);
    }


}
mysql_close($conn);
echo json_encode($return_arr);
?>

What you need to do is, when the autocomplete of the serial number is finished, run an ajax-call to retrieve the name and phone number based on the serial number and then populate those fields, something like this:

$('input[name=serial_number]').autocomplete({
    onComplete: function (val) {
        $.getJSON('/url-to-fetch-name-and-phone.php?serial_number=' + val, function (data) {
            $('input[name=name]').val(data.name);
            $('input[name=tel]').val(data.tel);
        });
    }
});

Obviously you'll need to change some function and variable names depending on your setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM