Michael Andrew Michael Andrew - 1 month ago 8
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 :

<?php

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

public function __construct()
{
parent::__construct();
}
}


Inside Controller :

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


AJAX :

$('#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)
{
console.log("ok");
}
, error: function(xhr, status, error)
{
console.log(status+" "+error+" "+xhr)
}
});


PROBLEM :

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

Answer

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()
    {
        parent::__construct();
    }

}

In the controller

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

Your javascript is fine as is.

If I use this

success: function (data) {
    console.log(data);
}

This is what the console reports

Object
  status: true
  topics: Array[3]
    0: "php"
    1: "stackoverflow"
    2: "json"
    length: 3