0

I'm very new to ajax/jquery and am trying to do something very simple: dynamically echo out the length of the user's new password as he or she types it out (in the paragraph tag, which I assigned an id of "test").

On one hand I have the following script and form:

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<script>
  $(document).ready(function() {

        $("input").keyup(function() {
            var npassword = $("input").val();
            $.post("pwd_ajax.php",{
                password: npassword 
            }, function(data,status) {
                $("#test").html(data);
            }); 
        });

  });
</script>

    <p id = "test"></p>

    <form action="" method="post">
        <table class="layout-tables">
            <tr>
                <th class="text-right">Current Password <span class="small">(needed)</span>: </th>
                <td><input type="password" name="cpassword" value="" size="30" /></td>
            </tr>

            <tr>
                <th class="text-right">New Password <span class="small">(optional)</span>: </th>
                <td><input type="password" name="npassword" value="" size="30" />
                </td>
            </tr>

            <tr>
                <th class="text-right">New Password Again: </th>
                <td><input type="password" name="napassword" value="" size="30" /></td>
            </tr>

and this is from my external file pwd_ajax.php

<?php
$new_pwd = $_POST['password'];

echo strlen($new_pwd);
?>

However, I consistently get '0' as an output. Where have I gone wrong? Any help would be much appreciated, thanks!

1
  • Instead of PHP you can calculate string length in java-script itself. Commented Jan 9, 2020 at 7:59

1 Answer 1

1

Declare id attribute (id="npassword")

<script>
  $(document).ready(function() {

        $("#npassword").keyup(function() {
            var npassword = $("#npassword").val();
alert(npassword);
            $.post("pwd_ajax.php",{
                password: npassword 
            }, function(data,status) {
                $("#test").html(data);
            }); 
        });

  });
</script>


  <tr>
            <th class="text-right">New Password <span class="small">(optional)</span>: </th>
            <td><input type="password" id="npassword" name="npassword" value="" size="30" />
            </td>
        </tr>
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of php you can calculate string length in java-script itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.