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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀