0

So, I have a js code calling a backend php script using ajax. The sole purpose of ajax is to send data(username and password) to the said php script. The php script will then query this data on the SQL server, and redirect to dashboard.html on success, or send a error message to the intial ajax request.

However, this is not what happens, and I cant find the source of error. So I tried some console logging and discovered that my SQL is correct and the ajax success function does get "Login Successful" echo if I remove the header() line. But with header() line present in php script, there is no data answer to ajax nor there a redirect to dashboard.html. Is there some concept which I'm missing?

var uname;
var pass;

$(document).ready(function() {
  $("#search_button").on("click", function() {
    uname = $("#username").val();
    pass = $("#password").val();

    if (uname == '' | pass == '') {
      $("#error_div").empty();
      $("#error_div").append('<p> Field cant be blank </p>');
      return;
    }

    $.ajax({
      url: 'back-end/login-script.php',
      data: ({
        'uname': uname,
        'pass': pass
      }),
      method: 'POST',
      success: function(data) {
        console.log(data);
        $("#error_div").empty();
        $("#error_div").append('<p>' + data + '</p>');
      }
    });

  });
});
<?php
    $host = "localhost";
    $db_name = "pwd_lkr_db";
    $tbl_name = "user";
    $username = $password = $_SESSION["errMsg"] = "";

    session_start();

    $username = $_POST["uname"];
    $password = $_POST["pass"];

    if(!empty($username) && !empty($password)) {
        //header("location: welcome.php");
        $connection = mysql_connect("localhost", "root", "");
        $db = mysql_select_db($db_name, $connection);
        $query = mysql_query("SELECT * FROM user WHERE password='$password' AND username='$username'", $connection);
        $rows = mysql_num_rows($query);
        if($rows == 1) {
            $_SESSION["sid"] = $username;
            echo "Login Successful";
            header("Location: dashboard.html");
            exit(); 
        } else {
            $_SESSION['errMsg'] = "Username or Password is not valid";
            echo $_SESSION['errMsg'];
            session_destroy();
        }

    } else {
        die("Username and Password are required!");
    }

?>

1 Answer 1

5

You cannot output text before using header(). Header() needs to be called before any content is sent back to the browser. Also, header() redirection won't work as you did a AJAX call. The redirect should be handled client-side, by returning a text response (JSON preferably...) with a way to tell the javascript that the login is fine, and provide the redirection uri.

Sign up to request clarification or add additional context in comments.

2 Comments

okay, so I got around it as you suggested, using redirection in js, but doesn't this make logins more vulnerable, since there is a check for success in source-viewable client-side js? Is there a better way to make entire login thing, including redirection back end using ajax and php?
You need to protect the dashboard.html page with some check, how depends on your structure and has nothing to do here; If you do calls to a PHP page, always check the user is authenticated first, otherwise decline any call to the "logged-in" page, i.e dashboard.html - This is not the place to chat about it, but I think you get what I mean

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.