1

On my ajax script when I login it is meant to be redirected to the dashboard.php file. But my current code is redirecting even if login fails (say I used a wrong username and password). How can I add a check on this? Say like if return message-success then redirect otherwise don't.

Ajax Script

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            username: $("#username").val(),
      password: $("#password").val(),
        };
    $.ajax({
            type: "POST",
            url: "login-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
        $('#loading-image').show();
      },
      complete: function(){
        $('#loading-image').hide();
      },
      success: function(html){
        $('.message').html(html).fadeIn(2000);
                setTimeout(function(){ window.location.replace("dashboard.php"); }, 2000);
            }
        });
        return false;
    });
});
</script>

login-process.php

<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');

$uname  = (!empty($_POST['username']))?$_POST['username']:null;
$pass   = (!empty($_POST['password']))?$_POST['password']:null;

if($_POST){
    $stmt = "SELECT * FROM members WHERE mem_uname = :uname";
    $stmt = $pdo->prepare($stmt);
    $stmt->bindValue(':uname', $uname);
    $stmt->execute();
    $checklgn = $stmt->rowCount();
    $fetch = $stmt->fetch();

    if($checklgn > 0){
        if(password_verify($pass, $fetch['mem_pass'])){
            session_start();
            $_SESSION['sanlogin'] = $fetch['mem_id'];
            $msg = "<div class='message-success'>Access Granted! Please wait...</div>";
        }else{
            $msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
        }
    }else{
        $msg = "<div class='message-error'>User not found. Please try again!</div>";
    }
}
echo $msg;
?>
  • When the php gets to the end of the file its successful, so with how you've got it you're always going to be successful. Your best option is as the answer below states. – Geoff Mar 19 '17 at 09:54

4 Answers4

0

The solution that'll require minimal efforts would be to just give an id to the response message box and check using the classes you've already provided:

$msg = "<div id='responseBox' class='message-success'>Access Granted! Please wait...</div>";

in case of error:

$msg = "<div id='responseBox' class='message-error'>Password mismatch. Please try again!</div>";

In your ajax callback, just check if the box contains the error class or the success class:

success: function(html){
    $('.message').html(html).fadeIn(2000);
      if($('.message').find('#responseBox').hasClass('message-success')){
          window.location.replace("dashboard.php"); }, 2000);
      }
    });
    return false;

}

Muhammad Ahsan Ayaz
  • 1,867
  • 10
  • 12
0

Try this one, i just refactored your code, i hope it will be helpful.

login-process.php

<?php
include'config/db.php';
// $msg = null;
$msg = array();
$date = date('Y-m-d H:i:s');

$uname  = (!empty($_POST['username']))?$_POST['username']:null;
$pass   = (!empty($_POST['password']))?$_POST['password']:null;

if($_POST){
    $stmt = "SELECT * FROM members WHERE mem_uname = :uname";
    $stmt = $pdo->prepare($stmt);
    $stmt->bindValue(':uname', $uname);
    $stmt->execute();
    $checklgn = $stmt->rowCount();
    $fetch = $stmt->fetch();

    if($checklgn > 0){
        if(password_verify($pass, $fetch['mem_pass'])){
            session_start();
            $_SESSION['sanlogin'] = $fetch['mem_id'];
            $msg['ok'] = TRUE;
            $msg['msg'] = "<div class='message-success'>Access Granted! Please wait...</div>";
            // $msg = "<div class='message-success'>Access Granted! Please wait...</div>";
        }else{
            // $msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
            $msg['wrong'] = TRUE;
            $msg['msg'] = "<div class='message-error'>Password mismatch. Please try again!</div>";
        }
    }else{
        // $msg = "<div class='message-error'>User not found. Please try again!</div>";
        $msg['notfound'] = TRUE;
        $msg['msg'] = "<div class='message-error'>User not found. Please try again!</div>";
    }
}
echo json_encode($msg);
?>

Ajax Script

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            username: $("#username").val(),
            password: $("#password").val()
        };
        $.ajax({
            type: "POST",
            url: "login-process.php",
            data: dataString,
            cache: true,
            dataType: 'json',
            beforeSend: function() {
                $('#loading-image').show();
            },
            complete: function() {
                $('#loading-image').hide();
            },
            success: function(html) {
                $('.message').html(html.msg).fadeIn(2000);
                if (html.ok) {
                    setTimeout(function() {
                        window.location.replace("dashboard.php");
                    }, 2000);
                }
            }
        });
        return false;
    });
});
</script>
Nik Lakhani
  • 207
  • 1
  • 10
  • your answer in too much appealing but its not working... just simply replaced your code with mine, checked everything, but its not working.. and now its not even logging in or showing success or error messages.. :( –  Mar 19 '17 at 11:59
  • 1
    I forgot to specify datatype as `json` in ajax request, now code is updated: `dataType: 'json'` check it out again! – Nik Lakhani Mar 19 '17 at 12:09
  • still not working.. I used the 2nd answer here to debug by using debugger and got this message in console `SyntaxError: missing : after property id`... Can you check with this once? –  Mar 19 '17 at 12:16
  • Yes, there is one more problem, `password: $("#password").val(),` on the above line we've to remove comma because it's a syntax error. so again i updated code, please try it, hopefully it should work now. – Nik Lakhani Mar 19 '17 at 12:21
  • what a silly mistake of mine.. should have removed.. I did not notice it.. but still NOT WORKING brother.. same error in console and save problem still persisting.. –  Mar 19 '17 at 12:31
  • jQuery code seems to be okay, so the remaining problem must be in PHP script. Please double check your PHP code, buddy. – Nik Lakhani Mar 19 '17 at 12:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138453/discussion-between-nik-lakhani-and-shubham-jha). – Nik Lakhani Mar 19 '17 at 12:54
  • Yeah sure, we'll continue there! – Nik Lakhani Mar 19 '17 at 13:18
0

A better approach would be to set an appropriate response status code and check the status code on the front end. Tying your font-end on the response text will mean you have to always remember to not change it (also doesn't work if you add localization).

In PHP you can set a status code with http_response_code. See this answer on how to do that: PHP: How to send HTTP response code?.

The appropriate status code for authentication can be 403 (Forbidden), 401 (Unauthorized), or even 404 (Not found).

On the font end, use the $.ajax callback for statusCode.

$.ajax({
  type: "POST",
  url: "login-process.php",
  data: dataString,
  cache: true,
  beforeSend: function(){
    $('#loading-image').show();
  },
  complete: function(){
    $('#loading-image').hide();
  },
  success: function(html){
    $('.message').html(html).fadeIn(2000);
    setTimeout(function(){ window.location.replace("dashboard.php"); }, 2000);
  }
  statusCode: {
    404: function() {
      console.log('user not found');
    }
  }
});
Community
  • 1
  • 1
squgeim
  • 2,321
  • 1
  • 14
  • 21
-1

You can take debugger and then check your process of code line by line.

You can use "debugger" which is part of javascript.

for example in your code you can take 2 or 3 debugger like:

    <script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            username: $("#username").val(),
      password: $("#password").val(),
        };
    debugger;
    $.ajax({
            type: "POST",
            url: "login-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
        $('#loading-image').show();
      },
    debugger;
      complete: function(){
        $('#loading-image').hide();
      },
      success: function(html){
        $('.message').html(html).fadeIn(2000);
                setTimeout(function(){ window.location.replace("dashboard.php"); }, 2000);
            }
        });
       debugger;
        return false;
    });
});
</script>

After make this changes you can run your code in browser and just press "Ctrl+Shift+I" then refresh your page and debug your code with pressing F10 key.

i am sure this will useful to you. thank you :)

Unknown_Coder
  • 764
  • 6
  • 24