duanjuete9206 2017-10-02 10:42
浏览 130
已采纳

自动填充表单不起作用

I want to make form, if i fill the first input (i.e 'rollnumber') , i want the rest of the input will filled automatically with data from mysql database (if the 'rollnumber' i filled is found in the database) And if the 'rollnumber' not found in database it will say "Rollnumber not found". How to achieve that goal?

The results with below code are:

  1. The autofill not working, data won't show even i fill the right 'rollnumber'
  2. the only thing that works is the #loading1, it show after i fill the data, but it won't hide back.

In case someone is kind enough to help me try my code to see what is wrong, here is the database (database name: login):

login.sql

These are my codes so far:

Form HTML:

<div class="form-group">
    <input type="text" name="rollnumber" id="rollnumber" tabindex="1" class="form-control" placeholder="Roll Number" value="">
    <img src="ajax-loader.gif" id="loading1"></img>
</div>
<div class="form-group">
    <input type="text" name="fname" id="fname" tabindex="1" class="form-control" placeholder="First name1" value="">
</div>
<div class="form-group">
    <input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last name" value="">
</div>
<div class="form-group">
    <input type="email" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
    <input type="text" name="phone" id="phone" tabindex="1" class="form-control" placeholder="Phone">
</div>
<div class="form-group">
    <input type="text" name="batch" id="batch" tabindex="1" class="form-control" placeholder="Batch">
</div>
<div class="form-group">
    <input type="text" name="lclass" id="lclass" tabindex="1" class="form-control" placeholder="Class">
</div>

Javascript:

$(document).ready(function()
{
    $("#loading1").hide();
    $("#rollnumber").change(function()
    {
            $("#loading1").show();
            var id = $("#rollnumber").val();
            var data = 'one=' + id;
            $.ajax
            ({
                type: "POST",
                url: "checkrollnumber.php",
                data: data,
                dataType: 'json',
                success: function (data) 
                {
                    $("#loading1").hide();
                    if (data) 
                    {
                        for (var i = 0; i < data.length; i++) { //for each user in the json response
                            $("#fname").val(data[i].fname);
                            $("#lname").val(data[i].lname);
                            $("#email").val(data[i].email);
                            $("#phone").val(data[i].phone);
                            $("#batch").val(data[i].batch);
                            $("#lclass").val(data[i].lclass);
                        } // for

                    } // if
                } // success
            }); // ajax
    });
});

checkrollnumber.php:

require_once "conn.php";
header('Content-type: application/json; charset=utf-8');
if(isset($_POST['one'])){
$json = array();
$id =  trim($_POST['one']);
$query = "SELECT fname, lname, email, phone, batch, lclass FROM users WHERE rollnum = ?";
$stmt = $DB_con->prepare($query);
    $stmt->bind_param('s', $id);
    $stmt->execute();
    $stmt->bind_result($nFname, $nLname, $nEmail, $nPhone, $nBatch, $nLclass);
while ($stmt->fetch()){
   $roll=array('fname'=>$nFname,'lname'=>$nLname,'email'=>$nEmail,'phone'=>$nPhone,'batch'=>$nBatch,'lclass'=>$nLclass);
    array_push($json,$roll);
}
echo json_encode($json, true);

 }

conn.php (connection)

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "login";


try
{
    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    $e->getMessage();
}
  • 写回答

2条回答 默认 最新

  • drema2014 2017-10-02 10:58
    关注

    You should return false if the rollnumber isn't in the database, so to do that you could check if the array is empty or not using count(), replace the following line :

    echo json_encode($json, true);
    

    By :

    if( count($json) == 0){
         echo json_encode("false", true);
    }else{
        echo json_encode($json, true);
    }
    

    Then is your JS code you should add a condition to show "Rollnumber not found" like :

    $(document).ready(function(){
      $("#loading1").hide();
    
      $("#rollnumber").on('input', function(){
        $("#loading1").show();
        var id = $(this).val();
    
        $.ajax({
          type: "POST",
          url: "checkrollnumber.php",
          data: {one: id},
          dataType: 'json',
          success: function (data) 
          {
            if (data == 'false') 
            {
                alert("Rollnumber not found");
            }else{
              for (var i = 0; i < data.length; i++) { //for each user in the json response
                $("#fname").val(data[i].fname);
                $("#lname").val(data[i].lname);
                $("#email").val(data[i].email);
                $("#phone").val(data[i].phone);
                $("#batch").val(data[i].batch);
                $("#lclass").val(data[i].lclass);
              } // for
    
            } // if
    
            $("#loading1").hide();
          } // success
        }); // ajax
      });
    });
    

    NOTE : The data parameter should be sent like data: {one: id}. I suggest also the use of input as event since it's more efficient when you track the use inputs :

    $("#rollnumber").on('input', function(){
    

    Hope it will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助