AJAX

Contents...

Many web applications today extensively use the AJAX mechanism for exchanging data with the server. Framework's system class waRequest offers method isXMLHttpRequest(), which allows you to determine whether a request has been received using AJAX:

waRequest::isXMLHttpRequest()  //returns true for AJAX requests and false otherwise

The contents of some web pages may be generated using only JavaScript functions. In such cases the server is relieved of the HTML code generation task using template files, and the implementation of the MVC's "View" layer is transferred to the client side. However, this adds the problem of transferring data to the client (web browser). Webasyst framework utilizes JSON as a convenient data transfer format for further processing by means of JavaScript.

To facilitate the transfer of data in the form of JSON structures, the framework offers base classes waJsonActions, waJsonAction, and waJsonController. When it is necessary to transfer JSON-packed data to the browser instead of pure HTML code, an action or a controller class extending one of these base classes should be created. The names of methods implementing the request processing logic should be written in accordance with the same rules as the names of methods of actions and controllers extending classes waViewActions, waViewAction, and waViewController.

A PHP array of data assigned to controller field response is automatically converted to a JSON structure and is transferred to the browser; e.g.,:

<?php

class someAppAjaxActions extends waJsonActions
{

    ...
    function testAction()
    {
        ...
        $this->response = array(
            'valA' => 'value first',
            'valB' => 'velue second',
        );
    }

}

The result of execution of the above action code will be a JSON array:

{
    "status":"ok",
    "data":{
        "valA":"value first",
        "valB":"velue second"
    }
}

Below is a simple example of calling such an action by means of JavaScript code:

$.getJSON('?module=ajax&action=test', function (json) {
	alert(json.data.valA);
});