Sharan Mohandas
Sharan Mohandas

Reputation: 871

Returning AJAX Success and Error

I have built a login script that uses AJAX to submit form data.

The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.

It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.

Incorrect Username/Password

HTML Result Div

<div id="user-result" align="center"></div>

Jquery

<script type="text/javascript">
    $(document).ready(function () {
        var form = $('#loginform');
        form.submit(function (ev) {
            ev.preventDefault();
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                cache: false,
                data: form.serialize(),
                success: function (data) {
                    if (data == "true") {
                        $("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
                        setTimeout(
                            function () {
                                window.location.replace("index.php");
                            }, 1500);
                    } else {
                        $("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
                    }

                }

            });
        });
    }); 
</script>

fn_login.php

<?php
{
    session_start();
    include_once 'db_connect.php';

    if (isset($_POST))
     {
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
        $logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

        $stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);


        $stmt->execute();
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($password);
        $stmt->fetch();


        // Check if a user has provided the correct password by comparing what they typed with our hash
        if (password_verify($logpwd, $password))
        {
            $sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
            $result = $conn->query($sql);
            $row=mysqli_fetch_array($result);
            $id = $row['id'];
            $conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");

            $_SESSION['manager_check'] = 1;
            $_SESSION['email'] = $row['email'];
            $_SESSION['fullname'] = $row['fullname'];
            $_SESSION['designation'] = $row['designation'];
            $_SESSION['id'] = $row['id'];
            echo "true";
        }
         else {
            die();
        }
     }
}

?>      

Can someone please point out the mistake in the code/practice.

EDIT

Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct

Upvotes: 4

Views: 2157

Answers (2)

Pupil
Pupil

Reputation: 23948

You have spaces after ?>

So, the AJAX response is having spaces after true.

Solution:

Remove ?> from the end of PHP file.

It will not affect any PHP functionality.

And you AJAX response will be without spaces.

Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.

Tips for debugging AJAX:

1) Always use Firefox (with Firebug Add) on Or Chrome.

2) Use Console tab of Firebug, to check which AJAX requests are going.

3) Here, you can see input parameters, headers and most important response.

4) So, in short you can debug a whole AJAX request life cycle.

Upvotes: 2

Dhinju Divakaran
Dhinju Divakaran

Reputation: 893

You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes

<?php
{
    session_start();
    include_once 'db_connect.php';

    if (isset($_POST))
     {
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
        $logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

        $stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);


        $stmt->execute();
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($password);
        $stmt->fetch();


        // Check if a user has provided the correct password by comparing what they typed with our hash
        if (password_verify($logpwd, $password))
        {
            $sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
            $result = $conn->query($sql);
            $row=mysqli_fetch_array($result);
            $id = $row['id'];
            $conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");

            $_SESSION['manager_check'] = 1;
            $_SESSION['email'] = $row['email'];
            $_SESSION['fullname'] = $row['fullname'];
            $_SESSION['designation'] = $row['designation'];
            $_SESSION['id'] = $row['id'];
            echo json_encode(array('success'=>true));
        }
         else {
            die();
        }
     }
}

AND JQuery becomes

<script type="text/javascript">
    $(document).ready(function () {
        var form = $('#loginform');
        form.submit(function (ev) {
            ev.preventDefault();
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                cache: false,
                data: form.serialize(),
                success: function (data) {
                    if (data.success) {
                        $("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
                        setTimeout(
                            function () {
                                window.location.replace("index.php");
                            }, 1500);
                    } else {
                        $("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
                    }

                }

            });
        });
    }); 
</script>

Upvotes: 0

Related Questions