3

I have a form that submits to the submit_ajax method when submitted via AJAX. Now, when I receive it as an AJAX request, I want to return a JSON object.

In this case, I have two options. What would be considered the right way to do it, following the MVC pattern?

Option 1 Echo it from the controller

class StackOverflow extends CI_Controller 
{   
    public function submit_ajax()
    {
        $response['status'] = true;
        $response['message'] = 'foobar';
        echo json_encode($response);
    }
}

Option 2 Set up a view that receives data from the controller and echoes it.

class StackOverflow extends CI_Controller
{
    public function submit_ajax()
    {
        $response['status'] = true;
        $response['message'] = 'foobar';
        $data['response'] = $response;
        $this->load->view('return_json',$data);
    }
}

//return_json view
echo json_encode($response);
1
  • 2
    I realize this isn't what you're asking, but just as a side note, the Output class provides a handy way to set the appropriate MIME-type for JSON responses: $this->output->set_content_type('application/json')->set_output(json_encode(array('foo' => 'bar'))); Commented Apr 25, 2012 at 12:29

3 Answers 3

3

The great thing about CodeIgniter is that in most cases it's up to yourself to decide which one you're more comfortable with.

If you (and your colleges) prefer to echo through the Controller, go for it!

I personally echo ajax replies through the Controller cause it's easy and you have all of your simple scripts gathered, instead of having to open a view file to confirm an obivous json_encode().

The only time I'd see it to be logical to use view in this case is if you have 2 view files that echo's json and XML for instance. Then it can be nice to pass the same value to these views and get different outcome.

Sign up to request clarification or add additional context in comments.

1 Comment

I do the same. I echo ajax through the controller.
2

The correct way according to the MVC pattern is to display data in the View. The Controller should not display data at any case.

MVC is often seen in web applications where the view is the HTML or XHTML generated by the application. The controller receives GET or POST input and decides what to do with it...

source: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Comments

1

Usually when you have to show something on success in ajax funnction you need flags means some messages. And according to those messages you display or play in success function . Now there is no need to create an extra view. a simple echo json_encode() in controller is enough. Which is easy to manipulate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.