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

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

Hi,

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.
   
Code:
echo json_encode($this->upload->data());

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

He uses :

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

I use :

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

I also saw somewhere online

Code:
$data = $this->load->view('theview',$data, TRUE);
$this->output->set_output($data);

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
Reply
#2

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

Code:
$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
Reply
#3

@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.
Reply
#4
Thumbs Up 

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

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

$this->output
               ->set_content_type('application/json')
               ->set_output(json_encode($data));
Reply
#5

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

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

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




Theme © iAndrew 2016 - Forum software by © MyBB