简体   繁体   English

使用 php mysql 使用 ajax 选择的数据填充输入字段

[英]Populate input field with value from php mysql selected data using ajax

I have dropdown list populated from php mysql select (load from a table named "userstable" that has two fields "name" and "email").我有从 php mysql select 填充的下拉列表(从名为“userstable”的表加载,该表有两个字段“名称”和“电子邮件”)。 I want to select a "name" from the php mysql dropdown list and using Ajax (json) gets the "email" for the user selected from mysql table and show it in a input field. I want to select a "name" from the php mysql dropdown list and using Ajax (json) gets the "email" for the user selected from mysql table and show it in a input field. The dropdown list works and I can select the name but the email info in not being populated in the input field called "email".下拉列表有效,我可以 select 名称,但 email 信息未填充在名为“电子邮件”的输入字段中。

The mysql database table: mysql数据库表:

userstable contains fields [name],[email]. userstable 包含字段 [name],[email]。

My index.php code:我的 index.php 代码:

<?php
    require_once("conection.php");
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Contact Form Validation using jqBootstrapValidation with Ajax PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>

<!-- Ajax function for getting email --> 
 <script>
$(document).ready(function(){
    $('#name').on('change',function(){
        var name = $(this).val();
        $.ajax({
            url : "getemail.php",
            dataType: 'json',
            type: 'POST',
            async : false,
            data : { name:name,email : email},
            success : function(data) {
                userData = json.parse(data);
                $('#email').val(userData.email);
            }
        }); 
    });
});
</script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Showing User Info</h3>
   <br />
   <form id="simple_form" novalidate="novalidate">
            <div class="row">
            <!--Dropdown list for selecting name --> 
              <div class="col-md-6">
                <div class="control-group">
                  <h3>User</h3>
                      <select required id="name" name="name"  class="form-control" onchange="showname(this.value)">
                      <option value="">Select User</option>
                        <?php include("userselect.php") ?> 
                      </select>
                </div>
              </div>
                <!-- input field for showing user email -->               
              <div class="col-md-6">
                <div class="control-group">
                   <h3>Email</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="email" id="email" class="form-control form-control-lg"  />
                        <p class="text-danger help-block"></p>
                    </div>
                </div>
              </div>           
          </div>
   </form>
  </div>
 </body>
</html>

This is the php code userselect.php for selecting user name for showing email:这是 php 代码 userselect.php 用于选择用户名以显示 email:

<?php

    $selectdata = "SELECT * FROM userstable ORDER BY name";
    $DoQuery = $connect->query($selectdata);

    while($register = $DoQuery->fetch_assoc()){

        echo "<option value='".utf8_encode($register["name"])."'";
        if ($_POST["name"]==$register["name"])
        {
            echo "selected";
        }
        echo ">".utf8_encode($register["name"])."</option>";
    }
// $connect->close();
?>

This getmail.php code for getting email to show:此 getmail.php 代码用于获取 email 以显示:

 <?php

     $connect = mysqli_connect("localhost", "root", "mysq1passw0rd", "users");

     $query = "SELECT * FROM userstable WHERE name = '".$_POST["name"]."'";
     $result = mysqli_query($connect, $query);
     while($row = mysqli_fetch_array($result))
     {
       $data["email"] = $row["email"];
     }

     echo json_encode($data);


    ?> 

Please, any ideas?请问,有什么想法吗?

Please remove a line your from your code请从您的代码中删除一行

line: userData = json.parse(data);行:userData = json.parse(data);

success : function(data) {
    userData = json.parse(data);
    $('#email').val(userData.email);
}

To

success : function(data) {
    $('#email').val(data.email);
}

because you are already json_encode in your getmail.php file.因为您的 getmail.php 文件中已经是 json_encode 了。

 echo json_encode($data); //your getmail.php

I'm seeing a couple basic issues that may or may not have anything to do with it.我看到了一些可能与它无关的基本问题。

  • the require_once at top having a possibly-typo'd conection.php , 1 'n' rather than 'nn'.顶部的 require_once 有一个可能错字的conection.php ,1 'n' 而不是 'nn'。
  • probably a best practice to put a space before "selected", ie " selected", in userselect.phpuserselect.php中的“selected”(即“selected”)之前放置一个空格可能是最佳实践
  • your code in the script calling getemail.php but your post referring to the file as getmail.php , ie no 'e'您在脚本中调用getemail.php的代码,但您的帖子将文件称为getmail.php ,即没有“e”
  • not sure why you would set "async = false", since this is definitely an asynchronous request (user-triggered, not on page load - that's the 'a' in 'ajax').不知道为什么要设置“async = false”,因为这绝对是一个异步请求(用户触发,而不是页面加载 - 那是 'ajax' 中的 'a')。
  • your getemail.php script is designed to produce a set of rows, but your ajax parsing assumes it's only getting one reply.您的getemail.php脚本旨在生成一组行,但您的 ajax 解析假定它只得到一个回复。 The JSON encoding may be trying to put a hierarchy around it to prepare for getting more than one row as output. JSON 编码可能试图在其周围放置一个层次结构,以准备获得多个行,如 output。

If none of that ends up mattering, then I'd try taking the unparsed output from the AJAX request and putting that in the email field (or just msgbox() it) to see if you're getting data back that looks right.如果这些都不重要,那么我会尝试从 AJAX 请求中获取未解析的 output 并将其放入 email 字段中(或者如果您返回数据,请查看它是否正确)。 That should help isolate the problem to whether it's in the request, the processing of the request, or the parsing of the reply.这应该有助于将问题隔离在请求、请求的处理或回复的解析中。

Lastly, never put your password in code snippets like that - god knows where all else you use that password and this handle.最后,永远不要把你的密码放在这样的代码片段中——天知道你在哪里使用这个密码和这个句柄。

Thanks to all, I changed Ajax fuction and getemail.php and now It works and I changed getdata.php for returning "email" and "age" of the user.感谢大家,我更改了 Ajax 功能和 getemail.php 现在它可以工作了,我更改了 getdata.php 以返回用户的“电子邮件”和“年龄”。

This my index.php file:这是我的 index.php 文件:

<?php
    include 'connection.php';
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Contact Form Validation using jqBootstrapValidation with Ajax PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqBootstrapValidation/1.3.6/jqBootstrapValidation.js"></script>
<style type="text/css">


select#select_ext {
  border-radius: 10px;
  border: 2px solid #73AD21;
  padding: 20px; 
  width: 250px;
  height: 150px;
color: #333;
color: red;  
}

select#name{
    background: white;
    border: 0.15em solid #57ABB8;
    border-radius: 1.15em;
    color: gray;
    cursor: pointer;
    font-size: 0.80em;
    height: 39px;
    text-indent: 5px;
    width: 160px;
}

select#namex{
    background: white;
  border-radius: 5px;
  border: 2px solid #73AD21;
    color: blue;
    cursor: pointer;
    font-size: 1em;
    text-indent: 5px;
    width: 200px;
    height: 40px;
}
</style>



<!-- Ajax function --> 
<script>
$(document).ready(function(){
  $('#name').on('change',function(){
  var name= $('#name').val();
  if(name != '')
  {
   $.ajax({
    url:"getemail.php",
    method:"POST",
    data:{name:name},
    dataType:"JSON",
    success:function(data)
    {

     $('#age').val(data.age);
     $('#email').val(data.email);
     alert("email: " + data.email);
    }
   })
  }
  else
  {
   alert("Por favor seleccione nombre grupo");
   $('#employee_details').css("display", "none");
  }
 });
});
</script>


 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Showing User Info</h3>
   <br />
   <form id="simple_form" novalidate="novalidate">
            <div class="row">
            <!--Dropdown list for selecting name --> 
              <div class="col-md-4">
                <div class="control-group">
                  <h3>User</h3>
                      <select required id="name" name="name"  class="form-control" onchange="showname(this.value)">
                      <option value="">Select User</option>
                        <?php include("userselect.php") ?> 
                      </select>
                </div>
              </div>
              <div class="col-md-4">
                <div class="control-group">
                   <h3>Age</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="age" id="age" class="form-control form-control-lg"  />
                    </div>
                </div>
              </div> 
                <!-- input field "email" for showing user email -->               
              <div class="col-md-4">
                <div class="control-group">
                   <h3>Email</h3>
                    <div class="form-group mb-0 pb-2">
                        <input type="text" name="email" id="email" class="form-control form-control-lg"  />
                    </div>
                </div>
              </div>           
          </div>
   </form>
  </div>
 </body>
</html>

This my userselect.php file:这是我的 userselect.php 文件:

<?php

    $selectdata = "SELECT * FROM userstable ORDER BY name";
    $DoQuery = $connect->query($selectdata);

    while($register = $DoQuery->fetch_assoc()){

        echo "<option value='".utf8_encode($register["name"])."'";
        if ($_POST["name"]==$register["name"])
        {
            echo "selected";
        }
        echo ">".utf8_encode($register["name"])."</option>";
    }
// $connect->close();
?>

This is getemail.php:这是getemail.php:

<?php
require_once("connection.php");

if(isset($_POST["name"]))
{

$name=$_POST["name"];


 $query = "SELECT * FROM userstable WHERE name = '".$_POST["name"]."'";
 $result = mysqli_query($connect, $query);
 while($row = mysqli_fetch_array($result))
 {
   $data["age"] = $row["age"];
   $data["email"] = $row["email"];
 }

 echo json_encode($data);
}

?>

Please, How can I do as "sal" suggests for getting the fields "name" and "email" in the selectuser.php file and show "email" in input field id="email" using ajax?请问,我该如何按照“sal”的建议在 selectuser.php 文件中获取字段“name”和“email”,并使用 ajax 在输入字段 id="email" 中显示“email”?

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

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