JSON view


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.


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

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
  • 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.

Previous: Smarty view
Next: CSV view

Table of Contents