Michael Andrew Michael Andrew - 1 year ago 89
Ajax Question

Convert CI_Model to JSON and then Send to AJAX

How to convert an object to JSON using json_encode and then send this JSON to AJAX as response?

CI_Model :


class TResponse extends CI_Model
private $status;
private $topics;

public function __construct()

Inside Controller :

$response = new Model\TResponse ();
$response->status = true;
echo json_encode($response);


$('#myform').on('submit', function (e)
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : 'My_Controller/exec', // form validation file
data : $('#myform').serialize (),
dataType: 'json',
success : function (data)
, error: function(xhr, status, error)
console.log(status+" "+error+" "+xhr)


When i execute that code result error. the error is "error Internal Server Error [Object object]". How to solve my problem?

Answer Source

I don't understand why you're using $response = new Model\TResponse();. It not "the codeigniter way" to load a model. But I think it must be related to the problem because the code belows works perfectly for me.

Notice I have made both class properties public. Private properties are not exposed and so would not be "presented" to json_encode().

class TResponse extends CI_Model
    public $status = FALSE;
    public $topics = ['php', 'stackoverflow', 'json'];

    public function __construct()


In the controller

$this->TResponse->status = TRUE;
echo json_encode($this->TResponse);

Your javascript is fine as is.

If I use this

success: function (data) {

This is what the console reports

  status: true
  topics: Array[3]
    0: "php"
    1: "stackoverflow"
    2: "json"
    length: 3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download