The correct way to echo when using AJAX with MVC (CodeIgniter)

I have a form that is submitted to the method submit_ajaxwhen submitted via AJAX. Now that I get it as an AJAX request, I want to return a JSON object.

In this case, I have two options. What could be considered the right way, following the MVC pattern?

Option 1 Echo from the controller

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

Option 2 Configure a view that receives data from the controller and echoes.

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);
+3
source share
3 answers

The great thing about CodeIgniter is that in most cases it’s up to you to decide which one is most convenient for you.

If you (and your colleges) prefer an echo through a controller, follow it!

ajax Controller, , , , , obivous json_encode().

, , , - 2 , echo json XML. .

+3

MVC - . .

MVC -, HTML XHTML, . GET POST , ...

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

+2

Usually, when you need to show something successful in ajax funnction, you need flags that mean some posts. And in accordance with these messages you show or play the function of success. Now there is no need to create additional viewing. a simple echo json_encode () in the controller is enough. It is easy to manipulate.

+1
source

All Articles