CLIFFORD P Y CLIFFORD P Y - 1 month ago 9
jQuery Question

How to separate view and data in Ajax response from codeigniter controller

I am sending data and view from codeigniter controller to ajax using code

$this->load->model('query_mainmodel');
$data['result'] = $this->query_mainmodel->getcategories();
print $this->load->view('add_content',$data,true);


and in ajax I have

$.ajax({
url: url,
type: 'POST',
dataType: "text",
success: function (response) {
tabID.html(response); //now this time response contains html only
}
});


I got html in response ,how can I get data from ajax.

Answer Source

You say you can get html, but now you want data. So in your controller, you can pass a view and data back as json:

$data['result'] = $this->query_mainmodel->getcategories();

echo json_encode( array(
    'view_html' => $this->load->view('add_content',$data,true),
    'data'      => $data['result']
));

Then in your JS:

$.ajax({
     url: url,
     type: 'POST',
     dataType: "json", // <- make sure to change this
     success: function (response) {
       // view HTML available like this
       console.log( response.view_html );

       // data available like this
       console.log( response.data );
     }
});