CodeIgniter Forums
What to return in controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: What to return in controller (/showthread.php?tid=69190)



What to return in controller - romankubis - 10-18-2017

Hello.
I would like to ask, what to return in controller if I am expecting XMLHttpRequest but request is not XMLHttpRequest.
I have something like this:


Code:
public function show_post($id)
{
 if (!$this->input->is_ajax_request())
   return false;
 ...
 $data = $this->some_model->post($id);
 return json_encode($data);
}

Is it good to return false or return other value?
Thank you.


RE: What to return in controller - dave friend - 10-18-2017

If you accept the premise that a controller's ultimate purpose is to send output to browser then you need to decide what output is appropriate to the situation you describe.

One thought is to not do anything.

PHP Code:
public function show_post($id)
{
 
   if($this->input->is_ajax_request())
 
   {
 
       $data $this->some_model->post($id);
 
       //do stuff
 
       return json_encode($data);
 
   }
 
   //controller returns without any output which results in a blank page


Another thought is to return an error

PHP Code:
public function show_post($id)
{
 
   if($this->input->is_ajax_request())
 
   {
 
       $data $this->some_model->post($id);
 
       //do stuff
 
       return json_encode($data);
 
   }
 
   //Pretend there is an ""Internal Server Error"
 
   $this->output
      
->set_status_header(500)
 
     ->set_header("Content-Type: text/plain")
 
     ->set_output("Internal Server Error");


This produces a very sparse page showing only the error message.

You could use CI's show_error function which outputs the standard error page.

PHP Code:
public function show_post($id)
{
 
   if($this->input->is_ajax_request())
 
   {
 
       $data $this->some_model->post($id);
 
       //do stuff
 
       return json_encode($data);
 
   }
 
   //Show the CI error page
 
    show_error("Internal Server Error"$status_code 500$heading 'Go away hacker!!!');


I would think the only questionable response is one that would give what is likely a hack attempt any clue as to why they got the output they did.


RE: What to return in controller - romankubis - 10-18-2017

Thank you Dave.
Maybe I was out of mind. It is so simple.