Client-Server Communication

Client-Server Introduction

Raxan's flexible client-server communication model makes it easier to build sophisticated web applications while taking advantage of the framework's integrated features.

In the client-server model, a client submits data to the web server via a GET or POST request. This data can be either a server-side event notification, a page request or form submit. Upon receiving the request, the server will process the data and then returns the result as an HTML or JSON formatted text.

The list below shows the main methods for sending and receiving data to and from the server.

TypeClient Method DirectionServer Method
Events Raxan.dispatchEvent()rightbind(), delegate(), registerEvent()
VariablesRaxan.getVar()leftregisterVar()
FunctionsAny JavaScript FunctionleftcallScriptFn()
ConduitsRaxan.createConduit()rightregisterConduit()

Events

Events are special actions that are used to invoke a callback method on the web server. These events can be triggered locally or remotely.

To receive server-side event notifications in Raxan you can use either bind(), delegate() or the xt-bind/xt-delegate attributes. Here's an example showing how to use bind()

<?php
    $this->button1->bind('click','.buttonClick');
?>

This will bind the callback method to the click event on the client.

When button1 is clicked the framework will call the buttonClick method on the server. See Server-side Events for more information.

Dispatching Events via JavaScript

To programmatically dispatch an event from the client, use can use the Raxan.dispatchEvent() method.

Raxan.dispatchEvent Syntax:

Raxan.dispatchEvent(option) - dispatch with an array of options
Raxan.dispatchEvent(type, fn) - dispatch with callback function
Raxan.dispatchEvent(type, value, fn)

Raxan.dispatchEvent Options:

  • type - Event type
  • target - Target element. Defaults to page or durrent document
  • targetWindow - Specifies the target window to display full-page event response.
  • view - Name of the page view to be loaded
  • url - Destination url. Defaults to current page
  • serialize - Selector or DOM elements to be serialized.
  • value - Value to be passed to the event. Can be any JavaScript data type.
  • complete - Callback function. Callback parameters: result, success, statusCode - HTTP Error Status Code. Only available when success is equal to false.

Example:

<script type="text/javascript">
    Raxan.dispatchEvent('click',value,function(result,success){
        alert(result);
    });
</script>

The Raxan.dispatchEvent() method is normally used to invoke a registered event:

<?php
    protected function _init() {
        // register the add item event
        $this->registerEvent('additem','.callbackFunction');
    }
?>

Dispatch the "additem" event from the client:

<script type="text/javascript">
    Raxan.ready(function() {

        // dispatch event with callback
        Raxan.dispatchEvent('additem',function(result, success) {
            if (!success) return false;
            alert(result);
        })

        // dispatch event while passing value and callback paramters
        var eventValue = 'Hello';
        Raxan.dispatchEvent('additem',eventValue,function(result,success) {
            if (!success) return false;
            alert(result);
        })

        // dispatch with options
        Raxan.dispatchEvent( {
            type :  'additem',
            view : 'form',
            value : 'some value here',
            serialize : '#form1',
            complete: function(result, success, statusCode) {
                if (!success) {
                    if (statusCode==404) alert('File not found');
                    else alert('Error while connecting to server: ' + result);
                    return false; // return false to prevent display of error message
                }
                // code here
            }
        })
    })
</script>

Variables

Registered variables provide a convenient way to send data to the client from the server. For example, You can send an array of items to the browser after the user has triggered an event:

<?php
    protected function sendData($msg) {
        // register the variable so that it can be available to the client
        $this->registerVar('msgVar',$msg);
    }
?>

You can use the following code to retrieve the content of the "msgVar" variable from the client:

<script type="text/javascript">
    Raxan.ready(function() {
        var msg;

        // retrieve msgVar
        msg = Raxan.getVar('msgVar');
        alert(msg);

        // retrieve and remove msgVar
        msg = Raxan.getVar('msgVar',true);
        alert(msg);
    })
</script>

The registerVar() method supports the following data types:

  • Booleans
  • Strings
  • Integers
  • Floats
  • Arrays
  • Objects

Functions

To call a JavaScript function from the sever use the callScriptFn() method as shown below:

<?php
    protected callback($e) {
        // call and pass a simple parameter to "some_function" on the client
        $param1 = 'Test message';
        $this->callScriptFn('some_function',$param1);

        // call and pass an  array parameter to "some_function" on the client
        $param1 = 'Colors';
        $param2 = array('red','green','blue');
        $this->callScriptFn('some_function',$param1,$param2);
    }
?>

Conduits (experimental)

A conduit forms a consistent data link between the client and the server so that data can be asynchronously access when needed. Conduits can also be used to download and cache very large dataset that can later be displayed within the browser.

A conduit must first be registered on the server then accessed from the client.

To create a conduit, use the registerConduit method as shown below:

<?php

    protected function _init() {
        $this->registerConduit('myDataset','.getData');
    }

    // data conduit handler
    protected function getData($offset, $limit, $params, &$rowCount) {
        $db = $this->Raxan->connect('mysql: host=local; dbname=testdb','user','password', true);
        // get row count
        if (!$rowCount) {
            $stmt = $db->query('select count(*) as total from customers');
            $rowCount = (int)$stmt->fetchColumn(0);
        }
        // get dataset
        $ds = $db->execQuery('select * from customers limit $offset,$limit');
        return $ds;
    }

?>

To connect to the above conduit use the Raxan.createConduit() method. This will return an instance to the Raxan.Conduit object:

<script type="text/javascript">
    // create connection to conduit
    var cn = Raxan.createConduit('myDataset');

    // get first record
    cn.first(function(row,index) {
        alert('The first customer is ' + row['name']);
    });
</script>

See Asynchronous Data Conduits for more information.


Up Next: Asynchronous Data Conduits