通过ajax从数据库获取信息并在html中显示

时间:2017-11-03 16:36:40

标签: javascript php html ajax mysqli

我在html fill中有两个输入元素 写入用户ID的第一个输入 第二个输入只是readonly来自数据库的用户名

当我在第一个输入中写入用户ID时,我使用ajax从数据库中通过user_id获取user_name的列,并在html中放入input元素的占位符

我的HTML代码是

<input type="text" name="user_id" id="user_id" placeholder="Write user ID"/>
<input type="text" name="user_name" id="user_name"placeholder="" readonly />

我的java脚本代码是

$(document).on('blur','#user_id',function(){
    var id_n = $(this).val();
    $.ajax({
        url:'ajax_load_user_name.php',
        type:'POST',
        data:'id='+id_n,
        success: function(data){
            if(data != ''){
// 
    // 1- here how to fetch result and put in placeholder or value of input element
// 2- all time is not fetch result
                    $('#user_name').html(data);
                }else{
                    $('#show').text('error fetch') ;// this is just for div show error
                }
            }
        });
      });

我的PHP代码

<?php
include "../include_db/db.php";

    $id_post = intval($_POST['id']);
    $out_put = '';
    GLOBAL $tf_handle;


        $sql = mysqli_query($tf_handle,"SELECT `user_name` FROM `users` 
                      WHERE `user_id` = '.$id_post.' ");

    $out_put = mysqli_fetch_assoc($sql);

    echo $out_put;
?>

我一直试图获取结果我不能 我不知道哪里出错了

每个人都充满了想法

在php文件中更新1

<?php
include "../include_db/db.php";

    if(!isset($_POST['id']))
        return false;

    $id_post = intval($_POST['id']);
    $out_put = '';
    GLOBAL $tf_handle;

    $sql = mysqli_query($tf_handle,"SELECT * FROM `users` WHERE `user_id` = '.$id_post.' ");

    while($rows = mysqli_fetch_assoc($sql) ){
        $name = $rows['user_name'];
        $out_put .= '<input type="text" name="order_recive_name" id="order_recive_name" class="form-control input-sm"
    placeholder="'.$name.'"  readonly />';
    }


    echo $out_put;
?>

0 个答案:

没有答案