JSON view


1Presentation

More and more websites are moving away from the classic static model according to which each interaction leads to a refresh of the page. Nowadays, web applications contain JavaScript code that communicates with the server through iAJAX technology.

Concretely, the JavaScript code sends requests to the server (often using a library such as jQuery), which in return sends a stream of data serialized in JSON easily usable by the client application.


2Usage

Imagine a piece of JavaScript code that would send information to the server, and use the returned data to modify the HTML page. In the following example, we are using the jQuery library for server connection and HTML manipulation:

// definition of the connection URL, by placing a parameter
var url = "/api/getUser/" + userId;

// send the request
$.getJSON(url, function(response) {
    // processing
    if (!response) {
        // communication error
        alert("Communication error.");
    } else {
        // we write the name of the user in a DIV
        $("#div-username").html(response.name);
    }
});

This request could be handled by a controller that differs very little from the usual controllers:

class ApiController extends \Temma\Web\Controller {
    public function getUser(int $id) {
        // recording of the data that will be sent
        // in the JSON stream
        $this['json'] = [
            'name' => 'Albert Einstein',
            'type' => 'genius',
        ];

        // set the used view
        $this->_view('\Temma\Views\Json');
    }
}
  • Lines 5 to 8 : The data to be sent in the JSON stream is defined by assigning it to the json variable.
  • Line 11 : We specify that the view to use for the outgoing data is the JSON view (and not the usual Smarty view).

Note: The JSON view obviously does not need templates, since it is the PHP data that is directly serialized.


3Download

If you want the JSON feed to be sent as a downloadable attachment, define a template variable named filename, containing the file name.

Example:

$this['filename'] = 'export.json';

4Debug mode

By default, the generated JSON stream is as compact as possible, serialized on a single line.

However, if a template variable named jsonDebug is set to true, the generated JSON stream will contain line breaks and indentations to make it easier to read.