为什么ajax没有将输入字段值传递给php解析器?

时间:2018-06-08 22:28:06

标签: php ajax forms

我正在构建一个帐户注册页面,该页面会根据数据库检查用户的电子邮件地址,以确保所述用户不会创建重复的帐户。使用ajax报告数据库中是否存在电子邮件。在表单中输入电子邮件地址时,我总是会收到“电子邮件正常”。这意味着它不存在于db中。但是,这是不正确的。如果我将电子邮件分配给php解析器中的变量,如$ email =“email@exists.com”,那么它实际上会报告正确的结果。我猜测解析器没有从表单中获取值以添加到查询中。你知道为什么这不起作用吗?

<input type="text" id="password" class="form-control" name="password" value="" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" placeholder="password" autocomplete="off" required />

的Ajax:

    <script>
function ajax_post(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "email_check.php";
    var fn = document.getElementById("firstname").value;
    var ln = document.getElementById("lastname").value;
  var e = document.getElementById("email").value;
  var pwd = document.getElementById("password").value;
    var vars = "firstname="+fn+"&lastname="+ln;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
}
</script>

和解析器:

<?php

include 'db.php';





$test= $_POST['email'];


  $sql="SELECT email FROM users where email = '$test' LIMIT 1";
   $result = mysqli_query($conn,$sql);

if(mysqli_num_rows($result) > 0)
{
echo 'email is in use.';
exit();

} else if(mysqli_num_rows($result) < 1){
echo 'email is ok';
  exit();
}


  ?>

2 个答案:

答案 0 :(得分:0)

您在发送请求时没有将电子邮件字段添加到您的变量中,在此行中:

\1

答案 1 :(得分:0)

您需要向解析器发送电子邮件,而不是firstname / lastname

var vars = "email="+e;