Search code examples
jqueryajaxcodeignitercodeigniter-2

get contents of Codeigniter's $this->output->set_output() via ajax


I'm creating an application using jQuery ajax and Codeigniter. Now, when my session expires it check's CI's $this->session->userdata('user_data') is empty if it's true I set it to header status 401 unauthorized. and should return the custom data being returned.

Here is my code:

if( empty($this->session->userdata('user_data')) ) {
        if($this->input->is_ajax_request()){
            $this->output
                ->set_content_type('application/json')
//set cutom output.
                ->set_output(json_encode( array('response_code' => 401, 'message' => 'unauthorized') ))
                ->set_status_header('401');
        }
        else {
            //redirect to login page
            redirect('login/logout');
        }
    }

as you can see I set the custom output as json. my ajax request is

   $(document).ajaxError(function(e,xhr,o) {
      // how can I fetch the contents from here?
   });
   var url = /*url for my controller */;
   var params = /* objects to be passed */;
   $.post(url, params).done(function(e){
     console.log('success');
   });

SOURCE: I found headers in CI documentation output class


Solution

  • Just answered my own question. thanks for the answer, it gave me an idea. the reason for this was it was the json was appended from the expected response. eg. expecting "hello!" as a response it gives me

     hello{'response_code': 401, 'message': 'unauthorized'}
    

    which I only need the json part. not the response string.

    What I did was on my php part where I check there is still an active session:

       if( empty($this->session->userdata('user_data')) ) {
            if($this->input->is_ajax_request()){
                $this->output
                    ->set_content_type('application/json')
                    ->set_status_header('401');
                    //I passed the data to die(). in order to disregard the previous response
                    // and get the expected response 
                    // {'response_code': 401, 'message': 'unauthorized'} 
                    die(json_encode( array('response_code' => 401, 'message' => 'unauthorized') ));
            }
            else {
                //redirect to login page
                redirect('login/logout');
            }
        }