简体   繁体   中英

aJAX call to PHP file

I have a need to use the $.ajax method to call a PHP file. I have to pass in a driver id to the PHP file, which then retrieves the id, executes a query to get the driver's name and return that name back to the form so I can autopopulate the appropriate textbox. Here is the ajax method:

var id=$('#DriverID').val();
    $.ajax({
        url: 'drivername.php',
        data: {driverid: id},
        type: 'POST',
        success: function(data) {
            $.('#DriverName').val(data);
        }
    });

Here's the PHP:

$driverid=$_POST['driverid'];


$host="Host to database";
$user="user"
$password="password";
$db="database";

$driver="";
$query="SELECT driver_name FROM drivers WHERE driver_id=$driverid";
$cn=mysqli_connect($host, $user, $password, $db);
$result=mysqli_query($cn, $query);
while($data=mysqli_fetch_array($result))
{
    $driver=$data['driver_name'];
}
echo $driver;

How do I configure the PHP file to return the driver's name, and also, is the ajax method syntax correct?

It looks like your PHP script is already returning the "driver's name" variable that you're setting up with your SQL. If your return value was larger or more complex (eg, multiple values, an array/object/etc), you could JSON encode it and use jQuery to JSON decode it. To update CSS id "DriverName" with the return data, I think you just have an extraneous ".":

success: function(data) {
    $('#DriverName').val(data);
}

This question is quite similar: jQuery ajax - update div

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