Monday, 17 October 2016

Returning a json object in codeigniter(flashdata)

There are three things that need to be kept in mind:
  1. The browser may cache the JSON response, so it's a good idea to append a time-stamp to the end of the URL to keep the data coming in fresh. (This is true of the GET method, not necessarily so with POST though).
  2. The content type of the JSON response needs to be "application/json" or "text/javascript".
  3. The json_encode function was included with PHP 5.2, so older environments may not be able to use it, and you'll have to either get the module installed or write your own encoding class.
I'm doing some work on a server running PHP 5.1.6, and I don't need to serialize any complex types, so I've found the technique shown below to work fine. I'm using a simple "JSON view" which sets the correct content type in the response header, and emits a JSON string which was manually concatenated in the controller.
Phil, jQuery effects/animations could make use of the returned JSON data in the success callback function. In the example below I'm just showing message in an alert box.
Client-side Code:

// the jQuery POST URL includes a time stamp
var now = new Date();
$.ajax({
    type: "POST",
    url: "page/post/" + now.valueOf().toString(),
    data: {},
    dataType: "json",
    success: function (result) {
        alert(result.message);
    }
});
Controller (/application/controllers/page.php):
class Page extends CI_Controller {

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

    function index()
    {
    }

    function post($TimeStamp)
    {
        /* process request... $Timestamp may or may not be used here. */

        $data['json'] = '{"message":"The post was handled successfully."}';
        $this->load->view('json_view', $data);
    }
}
View (/application/views/json_view.php):
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>

No comments:

Post a Comment