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);
$this->output->set_content_type('application/json')->set_output(json_encode(array('foo' => 'bar')));