Ext JS And PHP Sample

In this post I will demonstrate how you can use PHP to back your Ext JS-based user interface.

One of the advantages of Ext JS and other javascript frameworks is the degree of compartmentalization you can achieve between the user interface and other pieces of your website or application. The most visible of the different factors that promote this compartmentalization, is the physical separation among the deployed application modules — while the majority of business logic and data handling modules usually reside on the server, in general, the user interface lives within the confines of the browser.

It’s all about generating JSON

Reliable and efficient communications between the client-side and server-side elements of the system becomes a critical need in this scenario. Like most javascript frameworks, Ext JS uses JSON as its primary data interchange format. Regardless of the back-end technology you choose (PHP, .NET, Java, etc.), if you produce http responses containing JSON-encoded data, you will be able to relay information to Ext JS.

Let’s examine a couple of ways to create JSON-encoded data with PHP. For my examples, I will assume that I need to send to the browser the data needed to populate a combo box that will display a list of categories.

This is the definition of my Ext JS combo box:

var combo = new Ext.form.ComboBox({
    store: categoriesStore,
    displayField: 'name',
    valueField:'id',
    typeAhead: true,
    mode: 'remote',
    forceSelection: true,
    triggerAction: 'all',
    emptyText: 'Select a category...',
    selectOnFocus: true,
    applyTo: 'categories-combo'
});

The categoriesStore data store is a JsonStore that points to a PHP page where I will create the categories data:

var categoriesStore = new Ext.data.JsonStore({
    url: 'categories.php',
    root: 'categories',
    fields: ['id', 'name']
});

As defined in the store, the data will need to have a form similar to this:

{'categories':
        [{'id':'1', 'name':'Category 1'},
        {'id':'2', 'name':'Category 2'},
        {'id':'3', 'name':'Category 3'},
        {'id':'4', 'name':'Category 4'},
        {'id':'5', 'name':'Category 5'},
        {'id':'6', 'name':'Category 6'}]
}

The above is just a JSON representation of an object containing a categories array. Each array element is an object that represents a category, which in turn has two properties: id, and name. Our categories.php page will need to produce this data and send it to the browser.

Hand-crafting a JSON representation of an object

The first approach I will show you consists of hand-crafting the JSON representation of the categories object. Although PHP has facilities for creating JSON-encoded data, I recommend you try this approach as a way to get familiar with the JSON structures. This is how the PHP page would look like:

<?php
function GetCategories() {
    $categories = "{'categories':[";
    $categories .= "{'id':'1', 'name':'Category 1'},";
    $categories .= "{'id':'2', 'name':'Category 2'},";
    $categories .= "{'id':'3', 'name':'Category 3'},";
    $categories .= "{'id':'4', 'name':'Category 4'},";
    $categories .= "{'id':'5', 'name':'Category 5'},";
    $categories .= "{'id':'6', 'name':'Category 6'}";
    $categories .= "]}";
    return $categories;
}
echo GetCategories();
?>

In a more realistic scenario the categories information could have been obtained through a database call. Let’s assume I will use MySQL as the database and change the page like so:

<?php
function GetCategories() {
  $categories = "{}";
  $conn = OpenDbConnection();
  $query ="SELECT * FROM `categories`";
  $result=mysql_query($query);
  $num=mysql_numrows($result);
  if (0 != $num) {
    $i=0;
    $categories = "{'categories':[";
    while ($i < $num) {
      $id = mysql_result($result,$i,"category_id");
      $name = mysql_result($result,$i,"category_name");
      $categories .= "{'id':'" . $id . "','name':'" . $name . "'}";
      $i++;
      if ($i < $num) {
        $categories .= ",";
      }
    }
    $categories .= "]}";
  }
  CloseDbConnection($conn);
  return $categories;
}
echo GetCategories();
?>

Here I just transformed the query results into a JSON-encoded string in the form that my Ext JS ComboBox needs.

The second approach I want to show you uses a PHP facility for JSON-encoding strings.

Using PHP’s JSON manipulation functions

Json_encode($value) is a function that returns a string containing the JSON representation of a value. In the code below I create and populate a two-dimensional array that contains the categories information, which I then pass to the json_encode function.

<?php
function GetCategories() {
  $query = "SELECT * FROM `categories`";
  $categories = array("categories" => array());
  $conn = OpenDbConnection();
  $result = mysql_query($query);
  $num = mysql_numrows($result);
  $i = 0;
  while ($row = mysql_fetch_assoc($result)) {
    $categories["categories"][$i] = $row;
    $i++;
  }
  CloseDbConnection($conn);
  return json_encode($categories);
}
echo GetCategories();
?>

As you might have expected, using json_encode considerably simplifies creating JSON data. I encourage you to read its documentation to gain full understanding of its capabilities and limitations.

These examples are a good foundation for you to build upon when working with PHP and Ext JS. I hope you find them useful. And don’t forget that these approaches also apply when working with other javascript frameworks.

Where to find more information

You can find additional information on the subject of this post by visiting the Ext JS tutorials page and the PHP documentation.

About Jorge

Jorge is the author of Building a Sencha Touch Application, How to Build a jQuery Mobile Application, and the Ext JS 3.0 Cookbook. He runs a software development and developer education shop that focuses on mobile, web and desktop technologies.
If you'd like to work with Jorge, contact him at ramonj[AT]miamicoder.com.

Comments

  1. Thank you very much!

Speak Your Mind

*