1. Introduction.

 1.1 Presentation
               I wrote this guide thinking in the user's who want's develope dynamic application's with the  GWT (Google Web Toolkit)  in an AMP(Apache,MySQL,PHP) environment's. The basic idea is write a small and very simple application using  MySQL and PHP at the server side, and GWT for the client interfaze, using JSON for the communication between the client and the server.

1.2 About JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, PHP, Python, and many others. You will find useful information about JSON here  http://www.json.org

1.3 About GWT
GWT (Google Web Toolkit) it's a toolkit that allow to developer's write AJAX application using JAVA, thinking in a very simple way, GWT "translate" the JAVA Code in JavaScript code.You will find more useful information about GWT here  http://code.google.com/webtoolkit/

1.4 About this guide.
We going to develop a small application to search employees data in a MySQL DB, using the employee name as parameter.

 1. Working at the server side.

2.1 Database

      We use a single table database, the table going to be named 'directorio' (directory), we fill the table with the employees information:



2.2 The PHP Script
        In order to access the database content we write a PHP script. We retrieve the information and then use JSON to format it. For this we use the JSON PHP class, that can be downloaded from  http://pear.php.net/pepr/pepr-proposal-show.php?id=198. This class allow us to convert PHP values to JSON format and then send it to the browser.  We write a PHP script "index.php". Here is the code:


// Here we call JSON.php

// Then we do the query to the MySQL DB, and fetch the results
$conector = mysql_connect('', 'root', 'juan') or die(mysql_error());
mysql_select_db('JSONPHP') or die(mysql_error());

$sqlQuery = "SELECT * FROM directory WHERE name LIKE '". $_REQUEST['tosearch']. "%'";
$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
$i = 0;
while($row = mysql_fetch_array($dataReturned)){
// We fill the $value array with the data.
 $value{"item"}{$i}{"Employe Number"}= $row['enumber'];
 $value{"item"}{$i}{"Name"}= $row['name'];
 $value{"item"}{$i}{"Position"}= $row['position'];
 $value{"item"}{$i}{"Phone Number"}= $row['phnumber'];
 $value{"item"}{$i}{"Location"}= $row['location'];
// We use JSON.php for convert the data to JSON format and send it to the browser
$json = new Services_JSON();
$output = $json->encode($value);

And that's all. The output of the PHP script looks like the following:

"Employe Number":"110009",
"Name":"Juan Hurtado",
"Position":"System Analist",
"Phone Number":"81001121",
"Location":"Monterrey City"}]

 Let's go and work now in the client interfaze with GWT.

3. Working at the client side.

3.1 The JSON RPC example.

   Google offer some samples applications with GWT. One of this show us how to use GWT with JSON to request a  Yahoo service. We take this example as base to write our interfaze, the original google JSON RPC example can be downloaded from here.

 3.2 Making a new application.

   Using the projectCreator.cmd (This is included with the GWT) we build a new project:

 C:\>projectCreator.cmd -eclipse PHPJSON -out PHPJSON
Created directory PHPJSON\src
Created file PHPJSON\.project
Created file PHPJSON\.classpath



   Then we build a new application for eclipse using the  applicationCreator.cmd:


C:\>applicationCreator.cmd -eclipse PHPJSON -out PHPJSON com.juan.client.PHPJSON

Created directory PHPJSON\src\com\juan
Created directory PHPJSON\src\com\juan\client
Created directory PHPJSON\src\com\juan\public
Created file PHPJSON\src\com\juan\PHPJSON.gwt.xml
Created file PHPJSON\src\com\juan\public\PHPJSON.html
Created file PHPJSON\src\com\juan\client\PHPJSON.java
Created file PHPJSON\PHPJSON.launch
Created file PHPJSON\PHPJSON-shell.cmd
Created file PHPJSON\PHPJSON-compile.cmd


               The original  JSON RPC example bring to us with an classe's that allow use parse JSON document's. Copy the following files from the example to our "client" folder in our "src" folder:

  • JSONArray.java
  • JSONBoolean.java
  • JSONException.java
  • JSONNumber.java
  • JSONObject.java
  • JSONParser.java
  • JSONString.java
  • JSONValue.java

         We need replace the original package line in all this files for the package line of our project. Also we will need check the file  JSONParser.java and replace the path's (ILcom/juan/client/JSONValue).  Then we import the project to Eclipse as the  GWT documentation  show us.

 3.3 Working in the application.

        We build a new class called  JSONRequester, in this class we put the following method:

  public Widget initializeMainForm() {
     *  Here we initialize and setup a panel for use it as container for the search form and
     *  the results.
    FocusPanel fpn = new FocusPanel();
    Grid gd = new Grid(1,2);
    b1.addClickListener(new SearchButtonClickListener());
    gd.setWidget(0, 0, txtBox);
    gd.setWidget(0, 1, b1);

    return fpn;


         As you can see. A Focus Panel is called, then we attach a Grid to the Panel, this Grid contain all the Widgets to use, when the user click the button we call  to the SearchButtonClickListener class, the code of this class is the following:

  private class SearchButtonClickListener implements ClickListener {
 *  (non-Javadoc)
 * @see com.google.gwt.user.client.ui.ClickListener#

* onClick(com.google.gwt.user.client.ui.Widget)
      public void onClick(Widget sender) {
        * When the user click the button we fetch the URL.
        itemNumber = 0;

   private void doFetchURL() {
       * Here we fetch the URL and call the handler
      b1.setText("Searching ...");
        if (!HTTPRequest.asyncGet(DEFAULT_SEARCH_URL + "?tosearch=" + txtBox.getText(),

new JSONResponseTextHandler())) {


       This class contain the doFetchURL() method, who retrieve the URL an then call the JSONResponseTextHandler() class, with last class we manipulate the JSON document:

    private class JSONResponseTextHandler implements ResponseTextHandler {
     *  (non-Javadoc)
     * @see com.google.gwt.user.client.ResponseTextHandler#onCompletion(java.lang.String)
    public void onCompletion(String responseText) {
   *  When the fetch has been completed we parse the JSON response and
   *  display the result
     JSONObject jsonObject;
        try {
          jsonObject = JSONParser.parse(responseText);

        } catch (JSONException e) {


      private void displayJSONObject(JSONObject jsonObject) {
       * Here we clear the grid and fill it with the new values.
      private void requestChildrenGrid(JSONValue jsonValue){
        * Here we fill the grid.
      JSONObject jsonObject;
      if(jsonValue.isArray() != null){
       for(int i = 0; i < jsonValue.isArray().size();i++){
       childGrid.setWidget(itemNumber,0,new HTML("<HR/>"));
          childGrid.setWidget(itemNumber,1,new HTML("<HR/>"));
          int resizeNumber = itemNumber + 1;
      } else {
       if ((jsonObject = jsonValue.isObject()) != null) {
          String[] keys = jsonObject.getKeys();
          for (int i = 0; i < keys.length; ++i) {
            String key = keys[i];
            childGrid.setWidget(itemNumber,0,new HTML("<B>"+ key  +":</B>"));
            childGrid.setWidget(itemNumber,1,new HTML(jsonObject.get(key).toString()));
            int resizeNumber = itemNumber + 1;
        } else if (jsonValue != null) {
          // Only JSONObject, and JSONArray do anything special with toString, so
          // it is safe to handle all non-null cases by simply using toString
        } else {




      You will find all this methods in the file JSON.java in the JSON RPC google example. As you can see in the requestChildrenGrid(JSONValue jsonValue) method the JSON Document is divided in key's and value's, then format the key's with bold font and attach it to a grid, and then to the panel. Finally we edit the PHPJSON.java file and call to the JSONRequester to attach the result to the root panel.

   * This is the entry point method.
   public void onModuleLoad() {

  * Just for fun we use a TabPanel as layout
      TabPanel tp = new TabPanel();
   JSONRequester myJson = new JSONRequester();

   tp.add(myJson.initializeMainForm()  ,"Corporate Directory");




      And that's all, the final application looks like this:

      You can download the server and client code from here. Hope this little example be useful to you.  


Juan Hurtado