Using jMaki With PHP on OpenSolaris

Guest Author

by Ludovic Champenois

OpenSolaris is an operating system (OS), an open source project,
and a community. The project's goals are innovation, collaboration, and the extension of OpenSolaris technologies
such as Solaris OS, Sun's fully supported and tested enterprise operating system, as well as participation in the
development of OpenSolaris releases and distributions. Recently, the OpenSolaris open source project released the
OpenSolaris 2008.05 live CD operating system. The
CD includes a core operating system, kernel, system libraries, desktop environment, and a public repository-based package
management system called Image Packaging System (IPS). Using IPS, you can extend the operating system with code packages such
as Web Stack packages that add the latest versions of the Apache Web Server, MySQL database, PHP engine, code samples,
desktop tools, and user interface features.

One of the code samples bundled in the "webstackui" Web Stack package is
a simple web application that uses PHP, mySQL, and jMaki. This tip describes that application.
The application highlights the fact that developing PHP applications is relatively easy using OpenSolaris technologies.
Although the sample runs on the OpenSolaris OS, it also runs on the Linux, Mac OS, or Windows operating system with the
Apache, MySQL, PHP (AMP) stack of software.

The tip assumes that you're familiar with the basics of PHP and
mySQL. The
jMaki framework is a lightweight framework for creating Web 2.0
applications using standards-based technologies such as CSS, HTML, and JavaScript. The framework can be used in server
environments such as a JavaServer Pages (JSP) environment, a JavaServer Faces (JSF) environment, jRuby, or PHP. For an
introduction to jMaki, see the January 27, 2007 Tech Tip
Introduction to jMaki.

The Sample Application

Among its other features, the jMaki framework makes available widgets from popular JavaScript toolkits such as Dojo, Yahoo,
script.aculo.us, and Google in a way that's familiar to Java technology, PHP, or Phobos developers. These widgets
communicate within the jMaki framework through a mechanism called jMaki Glue which is built on top of a publish/subscribe event
mechanism. The April 15, 2008 Tech Tip
Working with jMaki Events
covered jMaki Glue and showed some examples of it in action. Let's take this
one step further by also showing how jMaki widgets can communicate with back-end logic. Specifically, let's create a simple
PHP web application that does the following:

  • Creates a MySQL database that contains one table -- a products table.
  • Provides an HTML form in which users can enter the necessary values for a product.
  • Uses a jMaki Yahoo table widget to display the list of products in the database.
  • Uses a jMaki button widget which users can click to add a product. This action inserts a new entry in the MySQL
    product table as well as in the displayed Yahoo table to reflect the new content of the database.

Figure 1 shows what the application displays to the user. Notice the table of products and the
add a product button.

A Web Page That Displays a Product Table and an Add a Product Button

Figure 1. A Web Page That Displays a Product Table and an Add a Product Button

Figure 2 shows what the application displays after the user enters information for a product
and clicks the add a product button.

Adding a Product to the Product Table

Figure 2. Adding a Product to the Product Table

Let's examine the major components of the application:

MySQL Database Configuration

A script named dbname.php is used by all the PHP files in the application to access the MySQL database. The
script specifies the database name and the credentials for access to the database and then connects to the database. It is
assumed that the MySQL server has been started on the server.

Here is the dbname.php script:

$mysql_connection = mysql_connect($dbhost, $username, $password);
if (!$mysql_connection)
die('Could not connect: ' . mysql_error());

Notice that the database name is phpwebstacksample and the username is root. There is no password.
The variable $mysql_connection refers to the correct database connection -- it is used in the other PHP files to
connect to the database.

Setup Script

A setup script, setup.php, is used when the application is run the first time and the database does not exist.
The script creates a simple database and a table named products within the database. Notice that the script
includes the dbname.php script at the beginning to access the MySQL database.

Here is the setup.php script (note that some of the code lines have been broken to fit the width constraints
of the page):

// Create database
if (mysql_query("CREATE DATABASE phpwebstacksample",$mysql_connection))
echo "Database created";
echo "Error creating database: " . mysql_error();
// Create table in my_db database
mysql_select_db($database, $mysql_connection);
$query="CREATE TABLE products (
id int(6) NOT NULL auto_increment,
name varchar(15) NOT NULL,
category varchar(20) NOT NULL,
price varchar(20) NOT NULL,
UNIQUE id (id),
KEY id_2 (id))";
echo "<br><br><br>Go back to the main index page to
<a href=\\"index.php\\">run the application ...</a>";

Main Page

The main page of the application, index.php, is responsible for connecting to the database,
displaying an HTML form to display the contents of the database in an Ajax-enabled Yahoo table widget,
and presenting a button to add a new product to the database. The button is an Ajax-enabled jMaki button. The application
uses jMaki Glue to enable communication between the button and the display table. When a user clicks on the
add a product button, a call is made to a server-side PHP function that inserts the new entry into
the MySQL table. In addition, a jMaki event is published. The event is consumed by the jMaki Yahoo table widget,
which then inserts a new row in the displayed table without doing a page reload of the entire page. This
demonstrates the power of Ajax to do asynchronous refreshes of parts of a page. It also demonstrates how the
jMaki Glue mechanism allows different widgets on a page to communicate.

Before you can use jMaki PHP widgets in a PHP script, you need to insert the following PHP statement at the
beginning of the page:

   <?php require_once 'Jmaki.php'; ?>

Then you can add widgets by calling the addWidget(...) function. The index page has two widgets and
so includes two calls to the addWidget(...) function.

Here's the code in index.php (note that some of the code lines have been broken to fit the width constraints
of the page):

   <?php require_once "Jmaki.php"; ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>Web Stack Sample Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="style.css">
if ( !mysql_select_db($database, $mysql_connection) ) {
echo "<br><br><br>The database for this sample does not exist.
<a href=\\"setup.php\\"> Click on the initialization link...</a>;
// Create the HTML Form with the 3 fields: name, category, and price of a Product Item:
<br>Using the following form, you can add products that will be inserted in
a MySql database, and displayed using jMaki Ajax framework in the table below.<br>
<form action="#" >
Product Name : <input id="name" name="name" type="text"><br>
Product Category :<input id="category" name="category" type="text"><br>
Product Price : <input id="price" name="price" type="text"><br>
<?php addWidget( array("name" => "yahoo.button",
"value" => "{ label : 'add a product' }"
// Create the Ajax jMaki table that displays the content of the MySQL database table:
// Notice the service parameter that calls a PHP script called ListProducts.php.
// This service will emit the content of the MySQL table into a JSON format that can
// be consumed with jMaki table:
echo "<b><center>List of Products:</center></b><br><br>";
addWidget( array( "name" => "yahoo.dataTable",
"args"=> "{columns : [
{ 'label' : 'name', 'id' : 'name'},
{ 'label':'category', 'id' : 'category'},
{ 'label': 'price ', 'id' : 'price'}

To better understand how the button action works, see the jMaki Glue File section. The code snippet
in the Glue file that pertains to the button click action is as follows:

   jmaki.subscribe("/yahoo/button/onClick", function(args) ...

When a user clicks the jMaki button, a jMaki event named /yahoo/button/onClick is sent to the jMaki event handling
mechanism and a callback specified in the jMaki Glue file is then executed.

Product List Script

The Product List script, lisProducts.php is responsible for retrieving the contents of the products table.
The script returns the contents as a collection of row entries in
JavaScript Object notation (JSON) format as follows:

name: 'value1', category: 'value2', price: 'value3'},
name: 'value1', category: 'value2', price: 'value3'},
name: 'value1', category: 'value2', price: 'value3'},
name: 'value1', category: 'value2', price: 'value3'},

In essence, the listProduct.php is a service available on the Web that returns data in JSON format to the
browser. Data returned in this format can then be rendered by the jMaki Yahoo table widget that was defined in the
index.php page.

Here is the lisProducts.php script:

if ( !mysql_select_db($database, $mysql_connection) ) {
<p>The database for this sample does not exist.</p>
<p>Please, run the <a href="setup.php>setup page.</a></p>
$query="SELECT \* FROM products";
echo "{'rows' : [";
while ($i < $num) {
"{ name: '".$name ."' , category :'".$category."', price :'".$price ."'}";
if ($i != $num -1)
echo ",";
echo "]}";

Add Product Script

The script named add.php is called when the user clicks the add a product button on the
main page. The script connects to the database and posts the new data to be added.
The script is in the button callback function that is defined in the glue.js script file.

Here is the add.php script:

@mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO products VALUES ('','$name','$category','$price')";
echo "value added";

jMaki Glue File

Finally, let's examine the jMaki Glue file, glue.js, that "glues" the parts of the application
together. The jMaki Glue file is the visible part of the jMaki publish/subscribe mechanism. You can learn more
about the jMaki publish/subscribe mechanism in the April 15, 2008 Tech Tip
Working with jMaki Events
and in the document jMaki Glue.

When a user clicks on the add a product button, the jMaki button widget publishes an event
to a topic named /yahoo/button/onClick. A listener in the glue.js file that is subscribed
to the /yahoo/button/onClick topic calls the add.php server-side script to insert the
new data into the MySQL database. To do that, the listener calls the jmaki.doAjax
function, which is executed asynchronously. The function specifies the service URL (add.php)
and the content to be added: name, category, and price (all are entry fields in the form on the main page).

The jmaki.doAjax function also specifies a callback function. After the add.php script
successfully inserts the data into the database, it calls the callback function. The callback function
publishes a new event to a topic named /yahoo/dataTable/addRow to add a new row in the jMaki Yahoo table.
This action updates the table with the new data inserted into the database.

Here is the glue.js file:

    // uncomment to turn on the logger
jmaki.debug = false;
// uncomment to show publish/subscribe messages
jmaki.debugGlue = false;
// map topic for the add Product button
jmaki.subscribe("/yahoo/button/onClick", function(args) {
// get the values of the 3 fields in the form:
var name= document.getElementById("name").value;
var category= document.getElementById("category").value;
var price= document.getElementById("price").value;
//do an ajax request to the add server side logic, with the correct params:
url : "add.php", // call the add.php URL
method : "POST",
content : {
name : name,
category : category,
price : price
callback: function(req) {
//in this call back, we just add a new row to the local jMaki table
if (jmaki.trim(req.responseText) == "value added")
jmaki.publish ('/yahoo/dataTable/addRow',
value: {
name : name,
category : category,
price : price
alert ("error adding a row: "+req.responseText);


By adding the jMaki Ajax framework to the fully integrated software stack provided by
OpenSolaris 2008.05, which includes a PHP engine,
an Apache Web Server, and a MySQL database, you can develop web applications that present modern Web 2.0 type behavior,
combining the power of a scalable operating system and the rich capabilities of Ajax technologies. The jMaki framework
hides the complexity of JavaScript and server-side PHP page rendering.

Further Reading

About the Author

Ludovic Champenois (ludo) is a principal engineer at Sun Microsystems. He is currently an architect for the
Java EE GlassFish Application and the OpenSolaris WebStack (AMP), focused on developer experience and tools integration.

Join the discussion

Comments ( 6 )
  • Caleb Payne Wednesday, July 2, 2008

    Why an article on PHP? I had a hard enough time trying to find out how to use jMaki with java .... and Sun puts out a tutorial on using jMaki with PHP. Seriously? And your previous article was on scripting languages and integrating them into java. I recommend reading the following article from JDJ:


    and then I recommend following his advice. Get. Back. To. Java. You guys seemed to have placed all of your energy on java (I mean you had to ... after all you DID change your ticker symbol to JAVA!) ... and now you're letting it go (whether you realize it or not). Stop with the silly shenanigans of trying to incorporate every feature of every language known to man into Java.

    Some of the more attractive features of java are it's platform independence, complete reverse compatibility and general steadfastness.

    As long as you continue to focus on java - and not these silly scripting languages (hint: not all java developers are web developers!!!!!!) - you'll be set.

    ..... and this is how I start my day .....

  • edort Wednesday, July 2, 2008

    Caleb: Thanks for the feedback. As the person who manages the Enterprise Tech Tips program, I want to assure you that comments like yours are taken very seriously.

    As you point out, the focus of the content on the java.sun.com site should be Java. However, we get lots of requests from the Java community to provide content that shows how to use Java with other languages, tools, and frameworks. We listen to those requests too.

    It's a difficult balancing act to satisfy the various needs. However we definitely do not want to get away from the primary focus -- Java.

    Ed Ort

    Sun Developer Network Editorial Staff

  • anshul Friday, July 4, 2008

    good article

  • shmilytsui Friday, July 4, 2008

    This's great!

  • Vicki Wednesday, July 9, 2008

    Thank you for this article. I am just starting out in amp development and learning it is a pleasure in Netbeans. I don't believe Java is diminished in any way by supporting or integrating alternatives. I don't wish to work with Mono or .net and I am happy with the direction Sun is taking.

  • haritha Wednesday, August 13, 2008

    this site is very informative

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.