Quick links: Content - sections - sub sections
EN FR
Jelix 1.7.15

Section: JSON

« AJAX ^ Web services JSON-RPC »
Switch to language: FR

Table of content

JSON is a data format using javascript syntax. This ease greatly the use of JSON encoded data in HTML content.

To send JSON data, there is a specific jResponseJson object. Its alias is "json". All you need to do is to assign your encoded json to the $data property:


  $resp = $this->getResponse('json');
  $resp->data = array( 'lastname'=>'dupont', 'firstname'=>'jean');
  return $resp;

To call the action, in raw javascript :


   var http = new XMLHttpRequest();

   //url is a variable which contains the url of the action
   http.open("post", url, true);

   http.onreadystatechange = function(){
	    if(http.readyState == 4){
	        // Get the data from the server's response
            var json = http.responseText;
            var value = JSON.parse(json);

            // do something with your json data
         
	    }
   };
   http.send(null);

or, with jQuery:


   $.getJSON( url, function (json) {
      // do something with your json data
   } 

With our example, the client will receive:


  { "lastname":"dupont", "firstname":"jean"}

And then the whole client process with jQuery is :


   $.getJSON( url, function (json) {
       alert(json.lastname + ' ' + json.firstname);
   });

A use case combined with jDao

In your controller:


$countryDao = jDao::get('common~country');
$countries = $countryDao->findAll();
$response = $this->getResponse('json');
$response->data = array();
foreach($countries as $country) {
	$response->datas[] = array('id' => $country->id , 'name' => $country->name);
}

The client will receive:


  { "id":20, "name":"Europe"}