− Table of content
Jelix supports json-rpc. This is a similar protocol to XML-RPC. The main differences is that data are JSON formatted instead of XML. (RPC = Remote Procedure Call)
Specific entry point ¶
A JSON-RPC request cannot be treated as a classic request, thus you can't use
"classic" request object. You have to create a specific
entry point in www/ directory, jsonrpc.php. This entry point should
instantiate a jJsonRpcRequest instead of a jClassicRequest.
Use the command app:create-entrypoint, by indicating the type jsonrpc:
php dev.php app:create-entrypoint --type=jsonrpc jsonrpc.php
It will create the entrypoint jsonrpc.php into your www/ directory,
and will declare it into the urls.xml and framework.ini.php files.
Then you retrieve an url for a jsonrpc action like this:
$url = jUrl::get("module~action@jsonrpc");
Controller ¶
As JSON-RPC is a specific request type, a controller filename must be suffixed by ".jsonrpc.php". A "default" controller file would be: "default.jsonrpc.php". (it can co-exists with a "default" classic controller such as "default.classic.php").
Controller content is similar to those of a classic controller. You just have to use a jResponseJsonRpc response (alias:"jsonrpc"):
class defaultCtrl extends jController {
function index(){
$resp = $this->getResponse('jsonrpc');
// any data types : integer, string, array, objects...
$data_php = ... ;
$resp->response = $data_php;
return $resp;
}
}
Client request ¶
To send a jsonrpc request, as specified in json-rpc spec, you have to use a specific json string:
{ method : "",
id:"",
params: {}
}
The method parameter indicates which action to execute. In a Jelix
application, it must be an action selector:
method:"myModule~default:index"
Data of the params parameter will be assigned to the params member of
your response. In your action, you will access them like this:
$parameters = $this->param('params');
Of course, $parameters will contain "php" datas. The JSON string is decoded
by jJsonRpcRequest..
In your HTML pages, you have to convert your Javascript data into a JSON string.
To do it, you should use the JSON object, and call its method stringify.
Pass the result to xmlHttpRequest to send the JSONRPC request to Jelix.
And to convert a JSON string to Javascript data, you should use JSON.parse().
An HTMl example:
var jsonrpc = { method : "myModule~default:index",
id:"1",
params: null
};
var toSend = JSON.stringify(jsonrpc);
var p = new XMLHttpRequest();
p.onload = null;
p.open("POST", "http://mysupersite.tld/jsonrpc.php", false);
p.send(toSend);
var response = JSON.parse(p.responseText);
var result = reponse.result;
And in your jelix action, if you do:
$resp->response = "hello";
In your javascript example, result variable content will be "hello".

