Skip to content
Advertisement

Why is this simple PHP login script not working?

I am very new to PHP and JavaScript and I have made a PHP and Javascript login script. However, it just shoots out Incorrect username or password. even though it’s correct. Here are my scripts:

PHP:

<?php
    header('Access-Control-Allow-Origin: *');
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if($username == "axqua" && $password == "abc")
    {
        $loggedin = true;
        echo "Logged in as axqua";
    }
    else
    {
        $loggedin = false;
        echo "Incorrect username or password.";
    }
?>

Javascript:

        <script>
            var username = document.getElementById("usernameform").value.toString();
            var password = document.getElementById("passwordform").value.toString();

            var formData = {'username':username, 'password':password}

            function posttourl() {
                var posts = $.ajax({
                    'url': 'http://example.com/',
                    'type': 'POST',
                    'data': formData
                })

                posts.done(function (res) {
                    console.log(res)
                })
            }
        </script>

HTML:

        <p class="text">Username</p>
        <input class="inputstyle" maxlength="12" id="usernameform">
        <br>
        <p class="text">Password</p>
        <input class="inputstyle" type="password" maxlength="16" id="passwordform">
        <br>
        <a href="#" class="button" onclick="posttourl()">Login</a>

I do not see a problem with this so I am not sure what is going on but if you can help then please do.

Advertisement

Answer

As confirmed by the comment, this is because the JS section run before the user entered the text (likely on page load), so

var username = document.getElementById("usernameform").value.toString();
var password = document.getElementById("passwordform").value.toString();
var formData = {'username':username, 'password':password}

are executed when the text boxes are empty, ignoring later input. Moving them into posttourl() ensure the values taken are current.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement