简体   繁体   English

使用AJAX将查询发送到php文件时,变量保持为空

[英]Variable remains empty when using AJAX in sending query to php file

I have a form in which I do some AJAX error handling before the form is submitted, just to improve user experience. 我有一个表单,在提交表单之前我会进行一些AJAX错误处理,只是为了改善用户体验。 My problem is that the variable $user_password seems to remain empty throughout the process, thus the error handling is irrelevant. 我的问题是变量$user_password在整个过程中似乎都为空,因此错误处理无关紧要。

In the following code, the first keyup function is to check if the password is longer than the minimum length and the second is to check if the passwords match: 在以下代码中,第一个键入功能用于检查密码是否长于最小长度,第二个用于检查密码是否匹配:

$(document).ready(function() {
    $("input[name=user_password]").keyup(function(){    
        var user_password = $("input[name=user_password]").val();
        //data to server...
        $.post("../server/hub.php", {
            //POST name and variable... 
            check_password: user_password
            //places fetched information...
        }, function(data, status) {
            $("#user_password").html(data);
        });
    });
});


$(document).ready(function() {

    $("input[name=user_password_2]").keyup(function(){
        var user_password = $("input[name=user_password]").val();
        var user_password_2 = $("input[name=user_password_2]").val();
        //data to server...
        $.post("../server/hub.php", {
            //POST name and variable... 
            password_match: user_password,
            password_match_2: user_password_2
            //places fetched information...
        }, function(data, status) {
            $("#user_password_2").html(data);
        });
    });

});

The variables are redirected to a php file where the error handling is actually conducted: 变量被重定向到实际执行错误处理的php文件:

if (isset($_POST['check_password'])) {
    $user_password = $_POST['check_password'];

    echo $user_password;

    if ($user_password == "") {
        echo "";
    } elseif (strlen($user_password) < 6) {
        echo "Password must contain at least six characters!";
    } else {
        echo "You are good to go!";
    }
}

if (isset($_POST['password_match'])) {
    $user_password = $_POST['password_match'];
    $user_password_2 = $_POST['password_match_2'];

    if ($user_password_2 == "") {
        echo "";
    } elseif ($user_password !== $user_password_2) {
        echo "Sorry, passwords do not match!";
    } else {
        echo "You are good to go!";
    }
}

Although the data returned to the html file remains empty and echoing the $user_password yields no result. 尽管返回到html文件的数据仍然为空,并且回显$user_password没有产生任何结果。

Here is the html segment: 这是html段:

<form action="../server/register.php" method="POST">
                        <div class="input_table">                           
                            <table>
                                <thead>
                                    <tr>
                                        <th><h1>Register to LIMS</h1></th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <tr>
                                        <td><input type="password" name="user_password" placeholder="Select Password"><p id="user_password"></p></td>
                                    </tr>
                                    <tr>
                                        <td><input type="password" name="user_password_2" placeholder="Repeat Password"><p id="user_password_2"></p></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <button type="submit" name="user_register" class="button_1">Register</button>
                        <button type="button" class="button_3">Cancel</button>              
                    </form>

Can anyone please explain why this is occurring? 谁能解释为什么会这样?

I was able to get your code to work as you have it written. 当您编写代码时,我能够使您的代码正常工作。

I created a blank page for the html called test.php : 我为html创建了一个空白页,名为test.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="../server/register.php" method="POST">

  <div class="input_table">
    <table>
      <thead>
        <tr>
          <th><h1>Register to LIMS</h1></th>
        </tr>
        </thead>
        <tbody>
          <tr>
            <td><input type="password" name="user_password" placeholder="Select Password"><p id="user_password"></p></td>
          </tr>
          <tr>
            <td><input type="password" name="user_password_2" placeholder="Repeat Password"><p id="user_password_2"></p></td>
          </tr>
        </tbody>
    </table>
  </div>

  <button type="submit" name="user_register" class="button_1">Register</button>
  <button type="button" class="button_3">Cancel</button>

</form>

<script>

$(document).ready(function() {
  $("input[name=user_password]").keyup(function(){
      var user_password = $("input[name=user_password]").val();
      //console.log('password 1 key up'); //Check for key up.. It works
      //data to server...
      $.post("hub.php", {
          //POST name and variable...
          check_password: user_password
          //places fetched information...
      }, function(data, status) {
          console.log(data); //Check for your data.
          $("#user_password").html(data); //Data was displayed in div.
      });
  });
});


$(document).ready(function() {

  $("input[name=user_password_2]").keyup(function(){
      var user_password = $("input[name=user_password]").val();
      var user_password_2 = $("input[name=user_password_2]").val();
      //data to server...
      $.post("hub.php", {
          //POST name and variable...
          password_match: user_password,
          password_match_2: user_password_2
          //places fetched information...
      }, function(data, status) {
          $("#user_password_2").html(data);
      });
  });

});

</script>

Notice that I use hub.php as the url for the AJAX. 注意,我使用hub.php作为AJAX的URL。

Another thing is that I was using Jquery 3.1.1 and I loaded the library before the form. 另一件事是我正在使用Jquery 3.1.1,并且在表单之前加载了库。

I also wrapped your jquery code in <script> tags. 我还将您的jquery代码包装在<script>标记中。

And the hub.php page which I placed in the same folder as test.php : 我放置在与test.php相同的文件夹中的hub.php页面:

<?php

echo 'I made it.';  //Test to see if you landed on the page.

if (isset($_POST['check_password'])) {
    $user_password = $_POST['check_password'];

    echo $user_password;

    if ($user_password == "") {
        echo "";
    } elseif (strlen($user_password) < 6) {
        echo "Password must contain at least six characters!";
    } else {
        echo "You are good to go!";
    }
}

if (isset($_POST['password_match'])) {
    $user_password = $_POST['password_match'];
    $user_password_2 = $_POST['password_match_2'];

    if ($user_password_2 == "") {
        echo "";
    } elseif ($user_password !== $user_password_2) {
        echo "Sorry, passwords do not match!";
    } else {
        echo "You are good to go!";
    }
}


?>

I would absolutely check your paths. 我绝对会检查您的路径。 If you don't see a response in the console your not directing your AJAX to the correct directory. 如果您在控制台中没有看到响应,则说明您未将AJAX定向到正确的目录。

I tested this and it works. 我对此进行了测试,并且可以正常工作。

roelofco - As you're not getting 404 error, it seems like there is no issue with the PHP file path. roelofco-由于没有出现404错误,因此PHP文件路径似乎没有问题。 Couple of things you can try out. 您可以尝试几件事。

  1. Please try adding the following code to the top of hub.php 请尝试将以下代码添加到hub.php的顶部

     <?php echo "Entering the Ajax File"; var_dump($_POST); 
  2. $("input[name=user_password]").val(); - This is not a good way to get the value. -这不是获得价值的好方法。 There are can be multiple elements/tags with same name present in an HTML document. HTML文档中可以存在多个具有相同名称的元素/标签。 So either you can change name attribute in html to id & change jquery accordingly, OR use $("input[name=user_password]").eq(0).val(); 因此,您可以将html中的name属性更改为id并相应地更改jquery,或者使用$("input[name=user_password]").eq(0).val(); - By this we are now telling JS to get the first element with the name user_password. -现在,我们告诉JS获得名称为user_password的第一个元素。

  3. Please note that Ajax calls on keyup is very costly. 请注意,Ajax调用keyup非常昂贵。 Try to do that in form submit. 尝试在表单提交中做到这一点。 Client side validation is fine during keyup. 客户端验证在键入过程中很好。

  4. Usage of mutiple DOM ready events will make the website slow. 使用多个DOM就绪事件将使网站变慢。 Its always ideal to keep all the code in a single DOM ready function. 将所有代码保留在单个DOM ready函数中始终是理想的选择。

  5. jquery post has fail & always callback methods. jQuery的职位失败和总是回调方法。 Try using that to get errors. 尝试使用它来获取错误。 In your case it will be like this. 在您的情况下将是这样。

     $.post("../server/hub.php", { //POST name and variable... password_match: user_password, password_match_2: user_password_2 //places fetched information... }, function(data, status) { $("#user_password_2").html(data); }).fail(function() { alert( "Some error" ); }).always(function() { alert( "Ajax finished" ); });` 

So the answer to the problem is quite simple but very easy to miss. 因此,该问题的答案非常简单,但很容易错过。 Again this shows why good coding practice is imperative for writing a successful website. 这再次表明了为什么编写成功的网站必须要有良好的编码习惯。 I seems that in this case the name=user_password was repeated somewhere else in the code, thus when called using: 我似乎在这种情况下, name=user_password在代码的其他地方重复了,因此在使用时被调用:

var user_password = $("input[name=user_password]").val();

it refered to input in another part of the code and not the input that I was trying to apply the code to. 它是指代码另一部分中的输入,而不是我尝试将代码应用于的输入。 Simply by changing name=user_password to name=user_password_1 in the html code and then changing the ajax code: 只需在html代码中将name=user_password更改为name=user_password_1 ,然后更改ajax代码即可:

$(document).ready(function() {
    $("input[name=user_password_1]").keyup(function(){  
        var user_password_1 = $("input[name=user_password_1]").val();
        //data to server...
        $.post("../server/hub.php", {
            //POST name and variable...
            check_password: user_password_1
            //places fetched information...
        }, function(data, status) {
            $("#user_password_1").html(data);
        });
    });


    $("input[name=user_password_2]").keyup(function(){
        var user_password_1 = $("input[name=user_password_1]").val();
        var user_password_2 = $("input[name=user_password_2]").val();
        //data to server...
        $.post("../server/hub.php", {
            //POST name and variable... 
            password_match_1: user_password_1,
            password_match_2: user_password_2
            //places fetched information...
        }, function(data, status) {
            $("#user_password_2").html(data);
        });
    });

});

The code works perfectly. 该代码运行完美。 Although this was, in my own opinion, an idiotic mistake, I still believe it to be important to post it as an answer so that other people may benefit from double checking their code for silly mistakes such as this. 尽管我个人认为这是一个愚蠢的错误,但我仍然认为将其作为答案发布很重要,这样其他人可以从仔细检查自己的代码中受益,例如这样的愚蠢错误。

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

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