Variable remains empty when using AJAX in sending

2019-09-02 01:05发布

I have a form in which I do some AJAX error handling before the form is submitted, just to improve user experience. My problem is that the variable $user_password seems to remain empty throughout the process, thus the error handling is irrelevant.

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:

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.

Here is the html segment:

<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?

3条回答
劫难
2楼-- · 2019-09-02 01:18

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:

<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.

Another thing is that I was using Jquery 3.1.1 and I loaded the library before the form.

I also wrapped your jquery code in <script> tags.

And the hub.php page which I placed in the same folder as test.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.

I tested this and it works.

查看更多
手持菜刀,她持情操
3楼-- · 2019-09-02 01:21

roelofco - As you're not getting 404 error, it seems like there is no issue with the PHP file path. Couple of things you can try out.

  1. Please try adding the following code to the top of 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. So either you can change name attribute in html to id & change jquery accordingly, OR use $("input[name=user_password]").eq(0).val(); - By this we are now telling JS to get the first element with the name user_password.

  3. Please note that Ajax calls on keyup is very costly. 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. Its always ideal to keep all the code in a single DOM ready function.

  5. jquery post has fail & always callback methods. 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" );
    });` 
    
查看更多
smile是对你的礼貌
4楼-- · 2019-09-02 01:34

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:

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:

$(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.

查看更多
登录 后发表回答