Andrew McCombs
Andrew McCombs

Reputation: 55

Ajax 200 Success/failed execution

I have an issue with ajax and I am kinda new at this. The issue that I am having is even if log in fails ajax is still running the success block of code. How do I direct the code to return a failed status.

I'm not asking for you to inspect my code just more as a reference. I just need to know how to tell my code to send anything other than a 200 for okay so that I can display the errors on the screen.

I type in false information and the ajax thinks that the login happened but it really didn't.

AJAX Section

jQuery(document).ready(function(){
document.body.style.paddingTop="3px";
$('a[href^="#fallr-"]').click(function(){
    var id = $(this).attr('href').substring(7);
    methods[id].apply(this,[this]);
    return false;
});
var methods = {  
    login : function(){
        var login = function(){
            var username = $(this).children('form').children('input[type="text"]').val();
            var password = $(this).children('form').children('input[type="password"]').val();
            var remember = $(this).children('form').children('input[name="remember"]').val();
            var token = $(this).children('form').children('input[name="token"]').val();
            if(username.length < 1 || password.length < 1 || token.length < 1){
                alert('Invalid!\nPlease fill all required forms');
                console.log(token)
            } else {
                var data = {
                    username: username,
                    password: password,
                    remember: remember,
                    token: token,
                }
                $.ajax({
                    type: "POST",
                    url: "login.php",
                    data: data,
                    dataType: "text",
                    success: function(data){
                        $('#error').append('Success');
                        // $.fallr.hide();
                        // window.location.href = "http://www.bettergamerzunited.com/members/";
                    },
                    error: function(data) {
                        $('#error').append('falied');
                    }
                });

            }
        }                        
        $.fallr.show({
            icon        : 'secure',
            width       : '400px',
            content     : '<h4 class="titles">Login</h4>'
                        + '<span id="error"></span>'
                        + '<form>'
                        +     '<input placeholder="Username" name="username" type="text"/'+'>'
                        +     '<input placeholder="Password" name="password" type="password"/'+'>'
                        +     '<input type="checkbox" name="remember" type="remember"/'+'> Remember Me'
                        +     '<?php echo $hidden; ?>'
                        + '</form>',
            buttons : {
                button1 : {text: 'Submit', onclick: login},
                button4 : {text: 'Cancel'}
            }
        });
    }
};
});

Login Section

require 'core/init.php';
if(Input::exists()) {
  if(Token::check(Input::get('token'))) {

    $validate = New Validate ();
    $validation = $validate->check($_POST, array(
        'username' => array('required' => true),
        'password' => array('required' => true)
    ));

    if ($validation->passed()) {

        $user = new User();

        $remember = (Input::get('remember') === 'on') ? true : false;
        $login = $user->login(Input::get('username'), Input::get('password'), $remember);
        $response = $login;
        echo $response;  // <-- Im going to have an if statement that determines if $login was true or false. But testing still.

    } else {
        foreach ($validation->errors() as $error) {
            echo $error, '<br>';
        }
    }
}
}

This is the class that handles the login.

public function login($username = null, $password = null, $remember = false) {

    if(!$username && !$password && $this->exists()) {
        Session::put($this->_sessionName, $this->data()->id);
    } else {
        $user = $this->find($username);

        if($user) {
            if($this->data()->password === Hash::make($password, $this->data()->salt)) {
                Session::put($this->_sessionName, $this->data()->id);

                if($remember) {
                    $hash = Hash::unique();
                    $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                    if(!$hashCheck->count()) {
                        $this->_db->insert('users_session', array(
                            'user_id' => $this->data()->id,
                            'hash' => $hash
                        ));
                    } else {
                        $hash = $hashCheck->first()->hash;
                    }

                    Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                }
                return true;
            } else {
                try{
                    throw new Exception('The Username or Password combination doesn\'t match. \n Please try again.');
                } catch(Exception $e) {
                    echo $e->getMessage();
                }
            }
        } else {
            try{
                throw new Exception('The Username you provide does not match anything in our system. Please Try again or Register.');
            } catch(Exception $e) {
                echo $e->getMessage();
            }

        }
    }

    return false;
}

Upvotes: 2

Views: 135

Answers (2)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

You can add below code for ajax error section ..in this way you will get idea of what's exactly is error and can debug it.

error: 
    function (XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
        alert(errorThrown);
    }
}

Upvotes: 2

chris85
chris85

Reputation: 23892

Use the PHP header function.

header('HTTP/1.0 403 Forbidden'); // or whatever status code you want to return.

There can be nothing else outputted before using the header function.

Upvotes: 1

Related Questions