Welcome Guest, Not a member yet? Register   Sign In
What to return in controller
#1

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.
Reply
#2

(This post was last modified: 10-18-2017, 07:52 AM by dave friend.)

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.
Reply
#3

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




Theme © iAndrew 2016 - Forum software by © MyBB