Welcome Guest, Not a member yet? Register   Sign In
How to return a view to an ajax call ?

(This post was last modified: 02-26-2015, 12:51 AM by Tao Pai Pai.)


I recently had to modify some code of my colleague. I saw that we don't handle ajax calls the same way.
When it's about returning data, we both use.
echo json_encode($this->upload->data());

However, when we have to return a whole view, we are a bit different :

He uses :

echo $this->load->view('theview',$data);

I use :

$view = $this->load->view('theview',$data, TRUE);
echo $view;

I also saw somewhere online

$data = $this->load->view('theview',$data, TRUE);

Those techniques seem to work correctly, but what the best pratices say about that ? Is one of them safer, faster or more "MVC friendly" ?

Thanks Blush

I would just load the view as normal, following the CI guidelines. That would be the simplest and fastest solution.

$this->load->view('my_view', $data);

No need to have echo in front, or place it in an variable and echo later.

More info about views: http://www.codeigniter.com/userguide3/ge...views.html

@silentium, Thanks for answering. Actually it's a bad copy/paste, there was indeed no echo in his part.
I've already read the doc, and there is no recommendation for that particular case. Probably because there is no need to I guess.
I will read the core function that load views to see if that third parameter can spare me some execution time.
Thumbs Up 

If you want to get a result in json, you can do so:

$data = $this->upload->data();


(This post was last modified: 03-01-2015, 10:58 AM by spjonez.)

Store it using a key so it's valid JSON:
$result = array(
    'view' => $this->load->view( 'theview', $data, true ),

$this->output->set_output( json_encode( $result ) );

Theme © iAndrew 2016 - Forum software by © MyBB