-1

I'm using the following code to send Ajax request to a PHP file:

var d = "email=" + email + "&password=" + password;

        $.ajax({
            url: "login/c_login_form.php",
            data: d,
            type: "POST",
            success: function(str) {

                        if ( str === "#" ) { //# means success
                            alert("Login successful!");
                            return;
                        }
                        else {
                            //login failed
                            alert("Error logging in: " + str);
                            return;
                        }
                     },
            error: function(obj) {
                        alert("Failed to send Ajax request.");
                        return;
                     }
        });

The contents of the PHP file are:

<?php
/*
*
* The controller file for login form
*
*/

if( isset( $_POST["email"] ) && isset( $_POST["password"] )) {

    $email = $_POST["email"];
    $password = $_POST["password"];

    //load the config file to read settings
    require_once($_SERVER['DOCUMENT_ROOT'] . '/hrms/lib/config.php');

    //connect to database
    $conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);

    if(!$conn) {
        echo "Can't connect to database";
        return;
    }

    //check if employee is active
    $query = "SELECT employee.emp_id, role, is_active FROM employee INNER JOIN user ON employee.emp_id = user.emp_id WHERE email_bb = '{$email}' AND password = '{$password}'";

    if( $query === FALSE ) {
        echo "Failed to query database.";
        return;
    }

    $result = mysqli_query($conn, $query);

    if( $result === false ) {
        echo "No such user exists. Please re-check login details.";
        return;
    }

    $row = mysqli_fetch_assoc($result);

    if( (count($row) > 0 ) and ($row['is_active'] == "0") ) {
        echo "Employee not active anymore. Please contact HR.";
        return;
    }

    if( count($row) === 3 ) {
        //Everything looks okay. Process login now.
        $emp_id = $row['emp_id'];
        $role = $row['role'];

        //close connection
        mysqli_close($conn);

        session_start();
        $_SESSION['emp_id'] = $emp_id;
        echo "#";

        $path = $_SERVER['DOCUMENT_ROOT'] . '/hrms/dashboard.php?role={$role}';
        header("Location://{path}");
        die();      
    }
}
else {
    echo "Error. POST is not set.";
    return;
}

Strangely enough, if I make the first two statements in the PHP file to be echo "#"; return; then I'm able to see the "Login successful" message. Otherwise, even when I send the correct query (verified in phpMyAdmin), I keep getting the error saying "Failed to send Ajax request".

Any idea what might be causing it?

ankush981
  • 5,159
  • 8
  • 51
  • 96
  • Open your browser's developer tools. Look at the Net tab. Look at the request you are sending. Look at the response you are getting. Use those to figure out what is actually happening, and then you can try to debug it. – Quentin Dec 01 '14 at 15:37
  • You should look up the [headers already sent](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) case - the query is not the problem – kero Dec 01 '14 at 15:37
  • 1
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Dec 01 '14 at 15:38
  • You are using [an unsuitable hashing algorithm](http://php.net/manual/en/faq.passwords.php) (i.e. none at all) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of your users' passwords. – Quentin Dec 01 '14 at 15:38
  • @Quentin Thanks for the heads-up. As this is a private project for now, I wanted to add hashing after figuring out how jQuery Ajax works. – ankush981 Dec 01 '14 at 15:42
  • @Quentin I'm on Chrome and checked the Network tab. I'm getting a strange cancelled GET request. Could you please help? http://postimg.org/image/87ls41j17/ – ankush981 Dec 01 '14 at 15:50
  • @kingkero Sorry, I'm new to web development. I'm not getting any warning message. Could it still be the case of headers already sent? – ankush981 Dec 01 '14 at 15:51
  • @dotslash First of all, you **cannot** have a `header` **after** a `echo`/`print`. Secondly, you are redirecting to `{path}` where you probably meant to use the variable `{$path}` – kero Dec 01 '14 at 16:07
  • @kingkero Damn! I intended to remove this PHP code and perform the redirection from JavaScript, but forgot. Thanks, it works now! :) – ankush981 Dec 01 '14 at 16:13

1 Answers1

0

Posting an answer so as to close this question. The problem was indeed related to headers already being sent, as I was using the echo and header functionalities in the same place. When I removed the header part and performed the redirection from JavaScript, it worked as expected.

ankush981
  • 5,159
  • 8
  • 51
  • 96