Reputation: 42450
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);
Upvotes: 3
Views: 3485
Reputation: 10996
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.
Upvotes: 3
Reputation: 14428
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
Upvotes: 2
Reputation: 19882
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.
Upvotes: 1