在php中选择下拉列表时,在多个文本框中获取数据库值

时间:2016-12-31 07:59:42

标签: php jquery mysql ajax

我有两页 add_admin.php ajax_admin.php 当我在下拉列表中选择名称时,它会在TEXTBOXES中显示FIRSTNAME,MIDDLENAME和LASTNAME。

这是我的代码:

add_admin.php

<!-- Department -->
<div class="col-xs-12 col-sm-12 col-md-12" >
<div class="form-group">
    <select id="faculty_name" name="faculty_name" class="form-control" onchange='fetch_select(this.value)' required>
        <option selected="selected" disabled="disabled">Please Select Faculty</option>
        <?php
            $query = mysql_query("select * from faculty_details");
            while($row = mysql_fetch_array($query))
            {
        ?>
        <option value="<?php echo $row['FACULTY_ID'];?>"><?php echo $row['FIRSTNAME']." ".$row['MIDDLENAME']." ".$row['LASTNAME'];?></option>
        <?php
            }
        ?>
    </select>
</div>
</div>

<!-- First Name -->
<div class="col-xs-12 col-sm-4 col-md-4">
<div class="form-group">
    <div class="input-group">
    <div class="input-group-addon"><i class="fa fa-fw fa-user"></i></div>
        <input type="text" id="fname" name="fname" class="form-control input-md" placeholder="First Name" value="">
    </div>
</div>
</div>

其他文本框中有中间名,姓氏

Ajax代码

function fetch_select(val)
{
    $.ajax
    ({
    type: 'post',
    url: 'ajax_admin.php',
    data: 
    {
        get_option:val
    },
    success: function (response) 
    {
        $('#fname').val(response);
    }
});

ajax_admin.php

<?php
    if(isset($_POST['get_option']))
    {
        $state = $_POST['get_option'];
        $find=mysql_query("select * from faculty_details where    FACULTY_ID=$state");
        while($row=mysql_fetch_array($find))
        {
        echo "$row[FIRSTNAME]";
        }
    }
?>

1 个答案:

答案 0 :(得分:1)

从服务器获取结果为json,以便您可以在jQuery中轻松使用它:
Ajax的admin.php的

if(isset($_POST['get_option']))
{
   $state = $_POST['get_option'];
   $row1=array();
   $find=mysql_query("select firstname,middlename,lastname from faculty_details where  FACULTY_ID=$state");

   while($row=mysql_fetch_array($find))
  {
    $row1[]=$row;
  }
  die(json_encode($row1));
}

Ajax代码

function fetch_val(val) {
    $.ajax({
        url:"ajax-admin.php",
        type:"POST",
        data:{"get_option":val},
        dataType:"JSON",
        success:function(data){
            $('#fname').val((data[0].firstname));
            $('#mname').val((data[0].middlename));
            $('#lname').val((data[0].lastname));

        }
    });
}