Fork me on GitHub

Processing Jaxon requests

No matter how many classes are exported to javascript, an application using the Jaxon library needs only one entry point to process all the requests to these classes.

This is the simplest code to process a request to a Jaxon class:

use function Jaxon\jaxon;

$jaxon = jaxon();
$jaxon->register(Jaxon::CALLABLE_CLASS, HelloWorld::class);


The processRequest() method calls the function or the class targeted by the request, and sends the returned response back to the client.

A more detailed example

In the following example, the code will be separated in multiple files, in order to have a more realistic example of Jaxon usage.

1. The class declaration

This file contains a class to be called with Jaxon. There can be many files like this one in the application.

// File HelloWorld.php

use function Jaxon\jaxon;

class HelloWorld
    public function sayHello($isCaps)
        $text = ($isCaps) ? 'HELLO WORLD!' : 'Hello World!';
        $response = jaxon()->newResponse();
        return $response;
2. The library initialization

This file defines the configuration options of the library.

// File setup.php
use function Jaxon\jaxon;

$jaxon = jaxon();

$jaxon->setOption('core.request.uri', 'ajax.php');

$jaxon->register(Jaxon::CALLABLE_CLASS, HelloWorld::class, ['include' => __DIR__ . '/HelloWorld.php']);

The HelloWorld class will be found thanks to the third parameter of the call. This parameter is optional, and not required when there is another mean to find the class, with autoloading for example.

3. Generating javascript code

The javascript and CSS codes generated by Jaxon must be inserted into the HTML code of the page to be rendered in the browser.

Recall that they are returned by the following calls.

use function Jaxon\jaxon;

$jaxon = jaxon();

$jaxonCss = $jaxon->getCss();
$jaxonJs = $jaxon->getJs();
$jaxonScript = $jaxon->getScript();

They can then be inserted in the HTML code of the page, like in the following example.

<!doctype html>
    <title>Jaxon Simple Test</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="/favicon.ico">

<?php echo $jaxonCss ?>

    <input type="button" value="Submit" onclick="JaxonHelloWorld.sayHello(1);return false;" />

<?php echo $jaxonJs ?>

<?php echo $jaxonScript ?>

4. Processing Jaxon requests

This file processes Jaxon requests.

// File ajax.php
use function Jaxon\jaxon;

require __DIR__ . '/setup.php';

$jaxon = jaxon();