samuraiseoul
samuraiseoul

Reputation: 2967

can't get json return in codeigniter

I have a login page, that sends a ajax request to the server when someone tries to log in. The ajax, goes to the server, cause they get logged in I've been able to confirm. But the problem is it seems my jQuery isn't receiving the JSON.

The function in my controller is:

public function login(){
    $this->load->model('users_model');
    if((!!$this->input->post('email')) || (!!$this->input->post('password'))){
        $ret = $this->users_model->login($this->input->post('email'), $this->input->post('password'));
        echo json_encode(array('status' => "OK", 'msg' => 'Logged in!')); //also tried return
    }else{
        echo json_encode(array('status' => 'FAIL', "msg" => 'Invalid Email or Pass'));
    }
}

and the AJAX function is:

<script type="text/javascript">
    $(document).ready(function() {
        $("#login").ajaxForm(function(json) {
            alert(json);
        if(json.status == true) {
                alert(json.msg);
            //window.location = '<?php echo base_url(); ?>';
            } else {
                alert("Problem");
                $(".error_msg").html(json.msg);
            };
        });
    });
</script>

if I alert the json variable, it's blank, and if I do json.msg it say undefined. So... what do I have to do to get this to give the callback, a json object, or an object of any kind? Please explain it so I understand the problem, not just how to fix it. Thanks a lot!

EDIT: Here's the form too:

<span class="error_msg"></span></br>

<form id="login" action="<?php echo base_url(); ?>users/login" method="POST" enctype="multipart/form-data">
    Email: <input name="email" type="text"/></br>
    Password: <input type="password" name="password"></br>
    <input type="submit"/>
</form>

Upvotes: 0

Views: 379

Answers (1)

000
000

Reputation: 27247

Ah, I think I understand.

Is this the plugin you are using? http://www.malsup.com/jquery/form/#api

In that case, use ajaxSubmit, not ajaxForm.

Other examples online do something like this:

$(document).ready(function() {
    $('#login').submit(function() {
    $("#login").ajaxSubmit({
        success: function(json) {
            alert(json);
            if(json.status == true) {
                alert(json.msg);
                //window.location = '<?php echo base_url(); ?>';
            } else {
                alert("Problem");
                $(".error_msg").html(json.msg);
            }
        }
    });
    return false;
    });
});

Upvotes: 1

Related Questions