简体   繁体   English

如何将获取的数据放在输入字段中-AJAX

[英]How to put the fetched data in the input field - AJAX

Im trying to live search or filter some data in my database using AJAX , I used the oninput event to trigger the function. 我试图使用AJAX实时搜索或过滤数据库中的某些数据,我使用了oninput事件来触发该函数。 But it's not working, can someone help me to find what's wrong in my code? 但这不起作用,有人可以帮我找出代码中的错误吗? Im just a beginner in ajax. 我只是ajax的初学者。

Here's my input field, 这是我的输入字段

   <div class="form-group">
               <label for="stud_num">Student Number</label>
                <input type="text" name="stud_num" class="form-control stud_num" oninput="loadinfo()" id="stud_num" placeholder="Student Number" style="max-width:150px;" required>
        </div> 

here's my function, 这是我的职能,

  function loadinfo(){
    var stud = $("#stud_num").val();
    $.ajax({
      url:'getrecords.php',
      method:'POST',
      data:{
        "loadinfo": 1,
        "stud": stud,
      },
      success: function(data){
        $('#firstname').val(data.firstname);
      }
    });
  }

here the php code, 这里的PHP代码,

   if(isset($_POST['loadinfo'])){
    $stud = $_POST['stud'];

    $sql = "SELECT * FROM studmast WHERE stud_no ='$stud'";
    $result = mysqli_query($con,$sql);

       while($row = mysqli_fetch_array($result)){
                  $data[] = array(
                        'lastname' => $row['lastname'],
                        'firstname' => $row['firstname'],
                        'midname' => $row['middlename']
                        );
            }
            echo $data;
   }

You can't echo a php array...you need to send a data format that can easily be consumed by client and the most common nowadays is json. 您无法回显php数组...您需要发送一种易于客户端使用的数据格式,而如今最常见的是json。

Use json_encode() to convert 使用json_encode()进行转换

Try 尝试

echo json_encode($data);

And make sure to set the dataType:'json in $.ajax 并确保在$.ajax设置dataType:'json

Because I cannot reply to comments yet.. @nethken as others have stated, use json_encode. 因为我还不能回复评论.. @nethken正如其他人所说,请使用json_encode。 Please ensure that data is being posted to the php file in question. 请确保将数据发布到有问题的php文件中。 You can confirm this by debugging the code in developer tools. 您可以通过调试开发人员工具中的代码来确认这一点。 Either step through the code or alert the value before sending (javascript client-side debugging). 逐步执行代码或在发送前警告值(javascript客户端调试)。

Next, I would var_dump($_POST['stud']) in your php file, this will confirm whether the value is getting there or not. 接下来,我将在您的php文件中使用var_dump($ _ POST ['stud']),这将确认该值是否到达那里。 You can see the data by going to the network traffic in your developer tools and selecting preview of the php file. 您可以通过在开发人员工具中进入网络流量并选择php文件的预览来查看数据。 If you have xDebug you can simply step through the code to debug, I'll assume you do not have it setup. 如果您有xDebug,则可以简单地逐步调试代码,假设您没有安装它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM