Using Ext.Direct in Ajax applications

Streamline client-side and server-side Ajax development using PHP

Ext.Direct, a feature of the ExtJS JavaScript framework that was introduced in version 3.0, lets you write applications that provide seamless communication between the client side and server side. By employing Ext.Direct, you can expose a list of server-side classes that can be called directly from the client-side code, making the process of building Asynchronous JavaScript and XML (Ajax)-style applications much simpler. This allows you to streamline client-side and server-side development, resulting in less code, less maintenance, and less bugs. In this article, learn how Ext.Direct works, and how to use it to work with PHP classes directly from a JavaScript application.

Share:

Joe Lennon, Lead Developer, Core International

Joe Lennon photoJoe Lennon is a 26-year-old mobile and web application developer from Cork, Ireland. Joe works for Core International, where he leads the development of Core's mobile HR self-service solutions. Joe is also a keen technical writer, having written many articles and tutorials for IBM developerWorks on topics such as DB2 pureXML, Flex, JavaScript, Adobe AIR, .NET, PHP, Python and much more. Joe's first book, Beginning CouchDB was published in late 2009 by Apress. In his spare time, Joe enjoys traveling, reading and video games.


developerWorks Contributing author
        level

12 October 2010

Also available in Chinese Japanese

Introduction

The concept of Ajax has allowed web applications to evolve from being slow, unresponsive, and counter-intuitive to behaving more like desktop applications, delivering instant feedback, removing the need for page refreshes, and facilitating a much better user experience all around. The problem with Ajax is that it adds an additional layer of complexity to application development. In an event-driven application, you might perform an action when a user clicks on a button. In traditional application development, you can put all of your logic for what this action should do right in the event handler, but with Ajax it's not that easy. You probably do some client-side validation, and if that is passed, you prepare your data and create a new Ajax request. You then define functions to handle a successful response and a failure. Then you must create the server-side code that will handle the Ajax requests and return a suitable response. This will probably need to be in a certain data format, such as JavaScript Object Notation (JSON) or XML, and you must provide it in such a way that the client side is expecting to receive it.

In short, Ajax development requires that a web application developer maintain a set of code both on the client side and on the server side, and there can be huge differences in how both work, making it difficult to debug and maintain. It would be great if developers had a way of calling server-side actions on the client-side, minimizing their exposure to all of the Ajax request and response handling. That's where Ext.Direct comes in.

At first, Ext.Direct may seem like an overzealous solution to a small problem, but by investing your time and effort in it at the start, you'll start to reap dividends later on. The initial hurdle of getting the building blocks of Ext.Direct working may seem complicated, but it typically only needs to be done once, and after that the changes needed to add new classes and methods are very straightforward. In this article, you learn how to get started and put the building blocks in place, and how to actually use Ext.Direct to call remote PHP methods from JavaScript. You then learn some of the more advanced features that Ext.Direct has to offer, and how to take full advantage of them in your own applications.


Prerequisites

This article uses Ext.Direct to communicate with PHP server-side scripts. If you do not have a working web server with PHP installed, the popular XAMPP package is available for Linux®, Windows®, Mac OS X, and Solaris. See Resources for links to install Apache, PHP, MySQL, and some other goodies.

To use Ext.Direct, you will need to download and extract the ExtJS JavaScript library into a location in your web server's document root. If you use XAMPP, look inside the XAMPP installation directory for a subdirectory named htdocs—this is your Apache document root. Create a directory named direct inside this directory. Now go to sencha.com (see Resources) and download the latest public release of ExtJS (3.2.1 at the time of writing). When the download completes, extract all files to the direct directory you just created. The final step is to rename the directory from ext-3.x.x to ext. I will refer to the directory in my code examples as ext to prevent inconsistency between versions (see Downloads to access the source code for the examples in this article).


Getting started with Ext.Direct

The best way to learn how Ext.Direct works is to jump right in and use it. At first, it might seem complicated, but when you have an understanding of the basics, its potential uses and power become very clear. In this section, you will learn how to create a basic web page that uses Ext.Direct to fetch the current date and time from the server using the PHP date function.

The configuration file

When you want to expose the methods in a server-side class to ExtJS using Ext.Direct, you must create a configuration file that defines the classes and methods available on the client side. This configuration can be a set of native key/value pairs in the programming language you are using, or alternatively can be a JSON or XML document. This example uses PHP arrays to avoid the need to parse JSON or XML. Open your favorite text editor and add the code from Listing 1 to it, saving the file as config.php in the direct directory you created earlier.

Listing 1. config.php—PHP configuration file for Ext.Direct classes and methods
<?php
$API = array(
    'Now'=>array(
        'methods'=>array(
            'getNow'=>array(
                'len'=>0
            )
        )
    )
);

The code in Listing 1 defines the API. The outer array contains a single key/value pair, with the key Now. This is the name of the PHP class that you want to expose, and consists of an array. This array contains a single member with the key methods, indicating that this contains the methods you are going to expose from the Now class. In the methods array there is a member getNow, which refers to the method that you are going to expose, getNow(). This itself is an array that defines the len property, which indicates the number of arguments the getNow() function accepts. In this case, you are not passing any arguments, so this value is 0.

The PHP class

Next, take a look at the corresponding PHP class file. Create a new directory in direct and name it classes. In this directory, create a new file named Now.php and add the contents of Listing 2 to it.

Listing 2. classes/Now.php—The PHP class that you will call from Ext.Direct
<?php
class Now {
    function getNow() {
        return date('jS F Y @ g:i:s a');
    }
}

As you can see, the class is named Now, which corresponds to the class name you declared in config.php. It has a single method, getNow(), which accepts no arguments. The getNow() function returns the current time in the format 27th August 2010 @ 12:21:34 pm.

The next block you need to put in place is the JavaScript API that exposes the methods available to Ext.Direct. You will write this API using PHP, loading the contents of the config.php file and generating a JSON version that Ext.Direct will be able to read and understand. This API is generic and does not need to be modified if you need to add more classes or methods. Later, you will see how the API is loaded in the web page itself.

The API

Create a new file named api.php containing the code in Listing 3.

Listing 3. api.php—dynamic JavaScript API for your PHP classes and methods
<?php
require('config.php');
header('Content-Type: text/javascript');

$actions = array();
foreach($API as $aname=>&$a){
    $methods = array();
    foreach($a['methods'] as $mname=>&$m){
        $md = array(
            'name'=>$mname,
            'len'=>$m['len']
        );
        if(isset($m['formHandler']) && $m['formHandler']){
            $md['formHandler'] = true;
        }
        $methods[] = $md;
    }
    $actions[$aname] = $methods;
}

$cfg = array(
    'url'=>'router.php',
    'type'=>'remoting',
    'actions'=>$actions
);

echo 'Ext.app.REMOTING_API = ';

echo json_encode($cfg);
echo ';';

This script first loads the config.php file, and specifies to the web browser that the content type of the output is JavaScript. You will actually load this file in your HTML page using a <script> tag, hence the output is treated as JavaScript. The config.php file declares a variable $API that contains key/value pairs with the classes and methods available to Ext.Direct. The script in Listing 3 scans the $API variable for these class and method names to define the actions available through JavaScript. A $cfg key/value array is then created to define the URL of the router (which you will create in a moment), the type (which is set to remoting), and the actions available. Finally, the JavaScript is output, defining Ext.app.REMOTING_API with the value set to the JSON representation of the $cfg variable. You will soon see what the browser will actually read from this file.

The router

The final component you need to put in place before you can actually use Ext.Direct to call server-side methods is the router. This piece of the puzzle takes the requests made by the client side to the server side and routes them to the required class. It then calls the appropriate method, passing in any arguments associated with that method. The router must handle two forms of request—a JSON encoded raw HTTP post, used for retrieving data; and a form post, used for updating data. If multiple requests are dispatched simultaneously, the HTTP post will be an array, and the router will need to route each individual request appropriately.

To create the router, create a new file and name it router.php, saving it in the direct folder. Its contents should mirror the code in Listing 4.

Listing 4. router.php—PHP script to route requests to the appropriate PHP class
<?php
require('config.php');

class ExtAction {
    public $action;
    public $method;
    public $data;
    public $tid;
}

$isForm = false;
$isUpload = false;
if(isset($HTTP_RAW_POST_DATA)) {
    header('Content-Type: text/javascript');
    $data = json_decode($HTTP_RAW_POST_DATA);
} else if(isset($_POST['extAction'])) {
    $isForm = true;
    $isUpload = $_POST['extUpload'] == 'true';
    $data = new ExtAction();
    $data->action = $_POST['extAction'];
    $data->method = $_POST['extMethod'];
    $data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null;    
    $data->data = array($_POST, $_FILES);
} else {
    die('Invalid request.');
}

function doRpc($cdata){
    global $API;
    try {
        if(!isset($API[$cdata->action])) {
            throw new Exception('Call to undefined action: ' . $cdata->action);
        }
        $action = $cdata->action;
        $a = $API[$action];

        doAroundCalls($a['before'], $cdata);

        $method = $cdata->method;
        $mdef = $a['methods'][$method];
        if(!$mdef){
            throw new Exception("Call to undefined method: $method on action $action");
        }
        doAroundCalls($mdef['before'], $cdata);

        $r = array(
            'type'=>'rpc',
            'tid'=>$cdata->tid,
            'action'=>$action,
            'method'=>$method
        );

        require_once("classes/$action.php");
        $o = new $action();

        $params = isset($cdata->data) && is_array($cdata->data) ? 
                                             $cdata->data : array();

        $r['result'] = call_user_func_array(array($o, $method), $params);

        doAroundCalls($mdef['after'], $cdata, $r);
        doAroundCalls($a['after'], $cdata, $r);
    } catch(Exception $e) {
        $r['type'] = 'exception';
        $r['message'] = $e->getMessage();
        $r['where'] = $e->getTraceAsString();
    }
    return $r;
}

function doAroundCalls(&$fns, &$cdata, &$returnData=null) {
    if(!$fns) {
        return;
    }
    if(is_array($fns)) {
        foreach($fns as $f) {
            $f($cdata, $returnData);
        }
    } else {
        $fns($cdata, $returnData);
    }
}

$response = null;
if(is_array($data)) {
    $response = array();
    foreach($data as $d) {
        $response[] = doRpc($d);
    }
} else {
    $response = doRpc($data);
}
if($isForm && $isUpload) {
    echo '<html><body><textarea>';
    echo json_encode($response);
    echo '</textarea></body></html>';
} else {
    echo json_encode($response);
}

There's quite a lot of code to the router, but like the API, it's generic code that does not need to be changed if you decide to add to the list any new methods or classes that are executable by Ext.Direct. At the beginning of the file a basic class is defined with four properties. This class will be used if the request made is a form post. Next, check if the request made includes raw HTTP post data; if it does, return a JSON-encoded response. Otherwise, instantiate the ExtAction class and assign the properties to the values in the form post data.

Next, there is a function named doRpc, which will figure out what classes and methods are being called by Ext.Direct, and load in the relevant class, calling the appropriate method passing it any supplied argument values. The doAroundCalls function will call any methods that are set to be called before or after an action. You are not using that in this case, so don't concern yourself with this too much right now.

At the end of the file, you build the response. If there are multiple requests, loop through the array of requests and call the doRpc function for each one. If there was only one request you simply call doRpc once. Finally, check to see if the request made was a form post or a file upload, in which case you output the data as a valid HTML page with the JSON-encoded output contained in a <textarea> HTML element. This is a requirement of the Ext.Direct specification for responding to form post requests. If the request was a raw HTTP post, simply issue a JSON-encoded response (you earlier defined the header for the response to use the MIME type text/javascript).

Calling the remote methods in JavaScript

With the configuration, PHP class API, and router all created, you can now go ahead and use Ext.Direct to call the getNow() function in the Now PHP class. Create a new file named first.php in your direct folder and add the code in Listing 5 to it.

Listing 5. first.php—your first Ext.Direct application
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ext.Direct Server Date/Time</title>
    <link rel="stylesheet" href="ext/resources/css/ext-all.css" />
    <script src="ext/adapter/ext/ext-base.js"></script>
    <script src="ext/ext-all.js"></script>
    <script src="api.php"></script>
</head>
<body>
<h1>Ext.Direct Server Date/Time</h1>
<script>
    Ext.onReady(function(){
        Ext.Direct.addProvider(Ext.app.REMOTING_API);

        Now.getNow(function(provider, response) {
            alert(response.result);
        });
    });
</script>
</body>
</html>

Listing 5 is a very straightforward HTML document. You simply include the regular ExtJS files (ext-all.css, ext-base.js and ext-all.js) in your <head> tag, as well as the remoting API that you created earlier (api.php). Then, you write some JavaScript that will add your API as an Ext.Direct provider, which will create the relevant JavaScript classes and methods that allow you to call your server-side PHP methods. Next, call your server-side method getNow from the Now class. Ext.Direct calls take a function as an argument, itself accepting two arguments: provider and response. The response argument contains the response that you receive from your server-side PHP script.

Running the project

Now that you have created all the code required for your first Ext.Direct application, let's go ahead and run the project to see the result it produces. Open your favorite Web browser and navigate to http://127.0.0.1:5984/direct/first.php. An alert message should pop up with the current date and time, as generated and formatted by PHP on the server side. This should look something like the window in Figure 1.

Figure 1. First Ext.Direct application in action
Screen showing 27 August 2010, 4:30 pm and an OK button.

If you are using a browser such as Firefox that allows you to click on links to external JavaScript files in your View Source view, click OK on the alert box to dismiss the message, and then right-click anywhere on the page and click View Source. Look for the following line: <script src="api.php">.

The api.php part of this line should be a clickable link. Clicking the link will bring you to the generated JavaScript source of api.php for the classes and methods defined in config.php. The source should contain something like the following: Ext.app.REMOTING_API = {"url":"router.php","type":"remoting","actions":{"Now":[{"name":"getNow","len":0}]}};.

This declares the configuration for Ext.app.REMOTING_API, which you then use as your provider when you try to use the exposed methods in your code.

Before you move on, let's investigate what would be required if one wanted to add a new class and a new method to be made available to Ext.Direct. In this case, let's create a new class named Server and a method in that class named getSoftware. This will respond with the details of the web server and PHP installation. First, create a new file named Server.php and save it in the classes subdirectory of the direct directory (alongside the Now.php file). Its contents are shown in Listing 6.

Listing 6. classes/Server.php—second class
<?php
class Server {
    function getSoftware() {
        return $_SERVER['SERVER_SOFTWARE'];
    }
}

The getSoftware method will simply return the value of the environment variable SERVER_SOFTWARE. Next, you need to modify config.php to tell Ext.Direct that this new class and method are available for remote calls. Change config.php so that its contents mirror that of Listing 7.

Listing 7. Updated config.php—referencing the new class and method
<?php
$API = array(
    'Now'=>array(
        'methods'=>array(
            'getNow'=>array(
                'len'=>0
            )
        )
    ),
    'Server'=>array(
        'methods'=>array(
    	      'getSoftware'=>array(
                'len'=>0
    	      )
        )
    )
);

As you can see, you have simply added the reference to the Server class, and you have defined that it contains the method getSoftware, which accepts no arguments. The final change you need to make is to your first.php file, where you actually perform the call to the server-side methods. In this case, you will simply show the response from the Server.getSoftware() method in a second alert box. In your first.php file, add the following lines in Listing 8 below the closing }); for the Now.getNow call.

Listing 8. The Now.getNow call
Server.getSoftware(function(provider, response) {
    alert(response.result);
});

Now go back to your browser and refresh the page. You should see the familiar date value pop up first. When you dismiss this message, you should see a second alert window, this time showing the server software information, as shown in Figure 2.

Figure 2. The response from your newly-added method
A window showing an Apache message and an OK button.

I think you'll agree that after you have laid the foundations, the process of adding new classes and methods is relatively simple. The final thing to check out is the generated JavaScript code produced by api.php, which should contain the code shown in Listing 9.

Listing 9. Generated JavaScript code produced by api.php
Ext.app.REMOTING_API =
 {"url":"router.php","type":"remoting","actions":{"Now":[{"name":"getNow",
 "len":0}],"Server":[{"name":"getSoftware","len":0}]}};

As you can see, this now contains the Server class with the getSoftware method, which is then used to make those functions available to you in JavaScript.

That covers the basics of how Ext.Direct works. In the next section, you will learn some of the more advanced concepts of Ext.Direct, including working with methods that accept arguments, returning more complex responses, and sending form data in the request rather than raw HTTP post data. You should then be ready to take what you have learned in this article and apply it to your own applications.


Next steps: more Ext.Direct concepts

In the previous section, you learned how to get started with Ext.Direct development. Before you are ready to take this knowledge and start building your own applications, however, there are some other concepts you should be familiar with. This section covers these concepts.

Accepting arguments in your methods

Both of the methods you exposed to Ext.Direct in the previous section were extremely basic and did not even accept any arguments. It is highly likely that you will need to pass arguments to the server-side functions you create, so let's see how you would adapt one of the functions to accept and use an argument.

First, open the config.php file you created earlier, and change the value of the len attribute in the getNow method reference from 0 to 1. This tells Ext.Direct that the getNow method is expecting 1 argument.

Next, you need to modify the Now.php class. Change the contents of this file to the code in Listing 10.

Listing 10. Revised classes/Now.php
<?php
class Now {
    function getNow($format) {
        return date($format);
    }
}

You'll notice that the function getNow now accepts a single argument, $format, and this argument is plugged into the call to the PHP date() function.

The final thing you need to do is modify the first.php file to actually pass an argument when calling the remote method. Look for the lines shown in Listing 11.

Listing 11. Modifying the first.php file
Now.getNow(function(provider, response) {
    alert(response.result);
});

To pass an argument to this method call, place the argument before the callback function as follows (see Listing 12).

Listing 12. Place the argument before the callback function
Now.getNow('jS F Y', function(provider, response) {
    alert(response.result);
});

Next, reload the browser window to see the changes. This time, the response for the getNow method call should only return the date and not the date and time, as shown in Figure 3.

Figure 3. Result of specifying date format in an argument
Screen showing 28th August 2010 and an OK button.

Next, you will see how to return something a bit more complex than a single value.

Returning complex result sets

Until now, the responses generated by your methods have all been single values. This is fine for basic functions, but in reality, you're likely to need to return complex types such as objects and arrays. Because your responses are in JSON format, this is very straightforward. Your PHP class methods can return arrays or key/value pairs, and the API you defined will automatically generate a JSON array or object from this. Let's look at a simple example. First, you need to modify your Server class, so open the classes/Server.php file and add the function shown in Listing 13.

Listing 13. Adding the getEnvVars() function to the Server class
function getEnvVars() {
    return $_SERVER;
}

Now, modify the config.php file to include this new method. The contents of the file should now mirror the code shown in Listing 14.

Listing 14. Revised config.php—adding new getEnvVars method
<?php
$API = array(
    'Now'=>array(
        'methods'=>array(
            'getNow'=>array(
                'len'=>1
            )
        )
    ),
    'Server'=>array(
        'methods'=>array(
    	      'getSoftware'=>array(
                'len'=>0
            ),
            'getEnvVars'=>array(
                'len'=>0
            )
        )
    )
);

Next, create a new file named second.php in your direct folder. You will use this as a new web page to call your newly created getEnvVars method. Add the contents of Listing 15 to this file and save it.

Listing 15. second.php—using the new getEnvVars method
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ext.Direct Complex Responses</title>
    <link rel="stylesheet" href="ext/resources/css/ext-all.css" />
    <script src="ext/adapter/ext/ext-base.js"></script>
    <script src="ext/ext-all.js"></script>
    <script src="api.php"></script>
</head>
<body>
<h1>Ext.Direct Complex Responses</h1>
<script>
    Ext.onReady(function(){
        Ext.Direct.addProvider(Ext.app.REMOTING_API);

        Server.getEnvVars(function(provider, response) {
            alert(response.result.DOCUMENT_ROOT);
            alert(response.result.HTTP_USER_AGENT);
            alert(response.result.MYSQL_HOME);
        });
    });
</script>
</body>
</html>

Now, open your browser and go to http://127.0.0.1/direct/second.php. You should see three pop-up windows, showing the location of your web server's document root, the user agent string for the browser you are using, and the location of the MySQL installation on your system (if there is one).

Sending form post data

In this section, you will learn how to send data to the server from a form, which will be sent in a form post request rather than a raw HTTP post. You will create a simple form with a single field Enter a number and a button with the text Validate. The goal is that the field will be validated on the server side to check that it is not empty and that the value is numeric. If it fails validation, you will display an error message to the user. Of course, you could do this with basic JavaScript, but in a real-world application, you could easily tweak this concept to validate input against a database to check if a requested user name was taken, for example.

For this example, you will create a new PHP class, NumberValidator, which will have a single method validateNumber. The first step is to add this new class and method to the config.php file. This is much the same as before, but you must indicate that the method is using a form handler rather than a raw post handler. Modify the config.php file so it matches the code in Listing 16.

Listing 16. Revised config.php—adding the NumberValidator class
<?php
$API = array(
    'Now'=>array(
        'methods'=>array(
            'getNow'=>array(
                'len'=>1
            )
        )
    ),
    'Server'=>array(
    	'methods'=>array(
    		'getSoftware'=>array(
    		    'len'=>0
    		),
    		'getEnvVars'=>array(
    		    'len'=>0
    		)
    	)
    ),
    'NumberValidator'=>array(
        'methods'=>array(
            'validateNumber'=>array(
                'len'=>1,
                'formHandler'=>true
            )
        )
    )
);

Next, you need to create the class. Create a new file and save it in the classes subdirectory as NumberValidator.php. Its contents are in Listing 17.

Listing 17. classes/NumberValidator.php—new validation class
<?php
class NumberValidator {
    function validateNumber($form) {
        $response = array();
        $num = $form['num'];
        if (strlen($num) < 1) {
            $success = false;
            $response['errors'] = array(
                'num'=>'Required field.'
            );
        } else if (!is_numeric($num)) {
            $success = false;
            $response['errors'] = array(
                'num'=>'Not a valid number.'
            );
        } else {
            $success = true;
        }
        $response['success'] = $success;
        return $response;
    }
}

This class is relatively straightforward. The values in the submitted form will be received as an argument. You will create a field with the name num, which you will validate. You then check if this field has any value at all or is not numeric, and, if either of these conditions hold true, you return an error. The method returns an object $response with a single member, success, with a value of true, should the number validate correctly, or it returns two members, success, with a value of false and an errors object with the relevant error message to be displayed for the field.

The final step is to create a new web page with the code to create the form and handle the submit event on the Validate button. Because this is an ExtJS tutorial, after all, let's use some ExtJS UI goodness in the process. Create a new file called third.php, and save it in your direct directory. Add the contents of Listing 18 to this file.

Listing 18. third.php—final example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
    <title>Ext.Direct Form Example</title>
    <link rel="stylesheet" href="ext/resources/css/ext-all.css" />
    <script src="ext/adapter/ext/ext-base.js"></script>
    <script src="ext/ext-all.js"></script>
    <script src="api.php"></script>
</head>
<body>
<h1>Ext.Direct Form Example</h1>
<script>
    Ext.onReady(function(){
        Ext.Direct.addProvider(Ext.app.REMOTING_API);

        Ext.QuickTips.init();

        var formExample = new Ext.form.FormPanel({
            title: 'Validation Form',
            padding: 10,
            buttons:[{
                text: 'Validate',
                handler: function(){
                    formExample.getForm().submit();
                }
            }],
            renderTo: Ext.getBody(),
            defaultType: 'textfield',
            items: [{
                fieldLabel: 'Enter a number',
                name: 'num',
                msgTarget: 'side'
            }],
            api: {
                submit: NumberValidator.validateNumber
            }
        });
    });
</script>
</body>
</html>

If you are familiar with ExtJS, you should understand this code. If you have not used ExtJS before, the code creates a new FormPanel (one of ExtJS's many beautiful UI controls) with a single button with the text Validate. An event handler for the button will cause the form to be submitted when the button is pressed. The code specifies that the form should be rendered to the document body of the page the code is executed on. This will append it to the bottom of the page (in this case, beneath the <h1> element. Next, the code defines the items that should appear in the form. For this example, there is a single item, the num field. Finally, the submit API is specified. In this case, you are using the NumberValidator.validateNumber Ext.Direct method, which will subsequently be called any time the form is submitted (when the Validate button is clicked).

With all the code created, launch your browser and point it to http://127.0.0.1/direct/third.php. You should see a nice form with a single field and a Validate button. First, leave the field empty and press the button. The field should highlight in red with an icon next to it, as shown in Figure 4. Move your mouse over the icon and you'll see the message Required field.

Figure 4. Form Example in action
Screen with an Enter a number field outlined in red.

Next, enter a valid number and press Validate. You'll notice that the field is no longer highlighted and the icon does not appear. Finally, enter an invalid number such as the text test and press Validate once more. The field will highlight once more and the icon tooltip will reveal the message Not a valid number.


Conclusion

This article provides a high-level introduction to Ext.Direct, showing you the basics of how to use it. First, you learned what Ext.Direct is, and what problems it aims to solve. Next, you learned about the various building blocks of an Ext.Direct application, namely the configuration, the API, the router, the PHP class, and the application file that uses Ext.Direct. In the process, you learned how to call Ext.Direct methods in your applications. You then learned how to pass arguments to your server-side methods, and how to return more complex data in your responses from the server. Finally, you learned how to handle form data, providing server-side validation based on form input.

There is much more to explore in Ext.Direct—see Resources for some links to other articles and guides on the topic. Right now, Ext.Direct is a young technology, so you can expect it to grow and become more feature-rich with time. By learning the basics now, you will have the foundation you need to usurp all the power Ext.Direct will offer in the future.


Download

DescriptionNameSize
Article source codeextdirectajax.source.zip6KB

Resources

Learn

Get products and technologies

  • Get ExtJS (3.2.1 at the time of writing), the cross-browser JavaScript library for building rich Internet applications.
  • XAMPP provides easy installation of Apache, PHP, MySQL, and other goodies.
  • Innovate your next development project with IBM trial software, available for download or on DVD.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=550159
ArticleTitle=Using Ext.Direct in Ajax applications
publish-date=10122010