1

I have problem with a log in form. When I try to log in the javascript always returns the false value even when I am typing correct username and password.

Here is my code in the jQuery file:

$(document).ready(function(){

var teamname = $("#teamname");
var teampassword = $("#teampassword");

function isPasswordCorrect()
{
    var password = teampassword.val();
    var name = teamname.val();
    var result = false;

    $.post('../php/validations/validatePassword.php', {tname: name, tpassword: password}, function(data){
        if(data == 1){
            result = true;
        }else{
            result = false;
        }
    });
    return result;
}

$("#join").click(function(){
    if(isPasswordCorrect()){
        alert("You have joined");
    }else{
        alert("You have not joined");
    }
});
});

Here is my code in the PHPfile:

<?php   
$teamname = $_POST['tname'];
$teampassword = $_POST['tpassword'];

if($teamname != "" || $teampassword !=""){
    include('../connection.php'); // Here is the log in to the phpmyadmin

    $queryCheckPassword = mysqli_query($con, "SELECT password FROM 
    teams WHERE    name = '$teamname'");

    $row = mysqli_fetch_row($queryCheckPassword);
    $teamPassword = $row[0];
    if($teamPassword == $teampassword)
    {
        echo 1;
    }else{
        echo 0;
    }
}
?>

And here is my code in HTML file:

<form id="joinform">  <!-- action="teams.php" method="post"> -->
    <ul>
        <div>
            <label>Team name&nbsp<font color='red'>*</font></label>
            <input type='team' name='teamname' id='teamname' placeholder='Team name' readonly='readonly'/>
            <span id='teamnameinfo'>Select an existing team</span>
        </div>
        <div>
            <label for="teampassword">Team password&nbsp<font color='red'>*</font></label>
            <input type='password' name='teampassword' id="teampassword" placeholder='Team password'/>
            <span id='teampasswordinfo'>Write team password</span>
        </div>
        <div>
            <button name='join' id='join'>Join</button> 
        </div>
    </ul>
</form>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 2
    **A**JAX is **Asynchronous** - the `result` variable operations are not quite that accurate. Please do the check inside the AJAX callback. – PeterKA Sep 30 '15 at 19:00
  • 2
    I hope that code isn't live on the Internet. If so, you should add some code to prevent SQL injection. – Kris Oye Sep 30 '15 at 19:01
  • 2
    You really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Here is an example [password test using AJAX](http://jayblanchard.net/putting_it_all_together.html) – Jay Blanchard Sep 30 '15 at 19:01
  • 2
    [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). – Jay Blanchard Sep 30 '15 at 19:02
  • Thank you for sharing me this useful information. I am going to check that. And of course I am not going to put this code on the Internet without SQL injection protection. Thank you again! – Georgi Karavasilev Sep 30 '15 at 19:13

3 Answers3

1

The problem lies in your use of Javascript. Look at your isPasswordCorrect function (which I have reformatted slightly to make the issue a little clearer):

function isPasswordCorrect()
{
    var password = teampassword.val();
    var name = teamname.val();
    var result = false;

    $.post(
        '../php/validations/validatePassword.php',
        {tname: name, tpassword: password},
        function (data) {
            if(data == 1){
                result = true;
            }else{
                result = false;
            }
        }
    );

    return result;
}

See that function (data) {} in there? That's a callback. The way the $.post method works is this:

  1. your JS code sends a request to the server using $.post

  2. your JS code continues, moving on to whatever comes next

  3. Some time later (could be 10 milliseconds later, could be 30 seconds later), the server responds to the request. At that point your callback is called.

What does this mean? When your code hits the return result; line, your code has just submitted the request to the server and the server has probably not responded yet. Thus, result is still false.

A quick solution to this problem is to move the alert statements into the callback, like this:

function isPasswordCorrect()
{
    var password = teampassword.val();
    var name = teamname.val();

    $.post(
        '../php/validations/validatePassword.php',
        {tname: name, tpassword: password},
        function (data) {
            if(data == 1){
                alert("You have joined");
            }else{
                alert("You have not joined");
            }
        }
    );
}

$("#join").click(function(){ isPasswordCorrect(); });

However, I imagine you're going to want to do more than just alert something. You're going to need to research the asynchronous nature of Javascript and understand it before you can extend this fragment to do much.

Kryten
  • 15,230
  • 6
  • 45
  • 68
0

Because AJAX does not return the result immediately - ASYNCHRONOUS - you want to do the check only and only when you have the result - in the AJAX callback like so:

function isPasswordCorrect()
{
    var password = teampassword.val();
    var name = teamname.val();
    $.post(
        '../php/validations/validatePassword.php', 
        { tname: name, tpassword: password }, 
        function(data) {
            if(data == 1) {
                alert("You have joined");
            } else {
                alert("You have not joined");
            } 
        }
    );
}

$("#join").click(isPasswordCorrect);
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

PeterKA is correct about the async. The default value (false) is probably be returning before your async call comes back. Try adding a callback instead (untested):

function isPasswordCorrect(callback)
{
    var password = teampassword.val();
    var name = teamname.val();

    $.post('../php/validations/validatePassword.php', {tname: name, tpassword: password}, 
          function(data) { callback(data == 1); });
}

$("#join").click(function(){
    isPasswordCorrect(function(result) {
        if (result)
           alert("You have joined");
        else
           alert("You have not joined");
    });
});
Kris Oye
  • 1,158
  • 14
  • 27