2

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?

6
  • It looks like you're doing it. What is the value of data? Commented Aug 22, 2017 at 2:57
  • now value of data in Ajax response is html,I edited code in ajax (data to response )for avoid confusion Commented Aug 22, 2017 at 3:05
  • What more or less are you expecting or hoping for? Commented Aug 22, 2017 at 3:08
  • I am expecting database query result including view Commented Aug 22, 2017 at 3:08
  • So you want two things, right? Commented Aug 22, 2017 at 3:10

1 Answer 1

3

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 );
     }
});
Sign up to request clarification or add additional context in comments.

1 Comment

By the way, you can do this for many things. Try it with 5 or 10 things. It is very powerful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.