Skip to content
Advertisement

how do pass $res from codeigniter model to my ajax function in view?

I want to verify user details from the table.My model looks like this:

public function validate_login(){
$this->db->where(
array(
'login_username' => $this->input->post('username'),
'login_password' =>$this->input->post('password'))
);
$query = $this->db->get('login')->num_rows();
if ($query > 0){
$res = true;
}
else{
$res = false;
}
return $res;
}

Here, when I try to echo $res, it does not bring any information on my view. My Controller looks:

 function validate_login()
    {
                $res = $this->bizmanager->validate_login();

                echo $res;

        }

This is where I want to pass the results from Model as an object and then help me to direct which page to load. My function in view is:

 $.ajax({
         type:"post",
          url: base_url + 'home/validate_login',//URL changed 
         data:{ 
              'username':username, 
              'password':password},
         success:function(data){                  
         if (result == true)
            {
            window.location ="home/home";
             }
         else{
            window.location ="home/load_register";
             }
          } 
       }); 

     $('#frmlogin').each(function()
        {
        this.reset();
        });

Advertisement

Answer

You’re doing everything right, but when you echo true or false it cannot be read by ajax response. Instead of setting $res to true false, set it to 1 and 0.

public function validate_login(){
    $this->db->where(array(
                'login_username' => $this->input->post('username'),
                'login_password' =>$this->input->post('password'))
                );
    $query = $this->db->get('login')->num_rows();
    if ($query > 0){
        $res = 1;
    }
    else{
        $res = 0;
    }
    return $res;
}

jQuery Code :

data variable of success callback will have your $res. You don’t need to pass it explicitly.

If $res is 1 it will redirect to “home/home” else to “home/load_register”

$.ajax({
    type:"post",
    url: base_url + 'home/validate_login',//URL changed 
    data:{ 
      'username':username, 
      'password':password
    },
    success:function(data){                  
        if (data === '1') {
            window.location ="home/home";
        } else {
            window.location ="home/load_register";
        }
    }
});
$('#frmlogin').each(function() {
    this.reset();
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement