PHP n AJAX Programming, Tools, Tutorials, Tips, Tricks

Thursday, March 22, 2007

Creating Web Apps using CPAINT AJAX Framework (PART I) - Example

Add to Technorati Favorites

AJAX is undoubtedly one of the most popular web development techniques (or technologies) these days. There are many web application frameworks for PHP that help developers and programmers create web applications using AJAX but the one that I felt comfortable using is CPAINT. Although CPAINT is not under active development now but it should still serve as a good starting point for developers who are new to AJAX. I haven’t tried all frameworks available, hence I cannot claim that CPAINT is the best but for me it is easy to use and flexible. Some nice features of CPAINT (according to their website) are as follows

  • Separation of Presentation and Logic

  • True to the AJAX Acronym

  • Single API, Multiple Languages

  • Easy, Flexible API

  • Greater Control of the XMLHTTP Object

  • Retrieval of Non-local or Non-CPAINT Files

DISCLAIMER: I have made every attempt to present accurate information, but I cannot guarantee that inaccuracies will not occur. I (the author) will not be held responsible for any claim, loss, damage or inconvenience caused as a result of any information found on this website (blog).


Follow the steps below:

  • Fire up your web browser and go to Download the CPAINT package. Most recent version of CPAINT as of this writing is 2.1.0.

  • Extract all files in a folder named “cpaint”.

  • CPAINT comes with two different types of files (i) for client side scripting i.e. javascript files and (ii) for server side scripting i.e. php files.

  • We will be working with the files under lib directory.

  • Also, for this tutorial, I’ll only work in a folder named “cpaint_test” on the server.

  • Copy the following 4 files from cpaint/lib/ to “cpaint_test” on the server.

    • cpaint2.config.php



    • json.php

  • Now, create a new file named index.php inside cpaint_test. In head section of index.php add the code below:

<script language="javascript"

src="./" type="text/javascript"></script>

  • Installation is complete. Now, we’ll write a simple program that uses CPAINT.

A simple AJAX program:

This is a simple calculator that takes two integers as input, calculates their sum using PHP, and shows the result to the user.

Enter the code below in body section of index.php.

<input id="first_input" type="text" size="5" /> +

<input id="second_input" type="text" size="5" /> =

<input id="result" type="text" size="7" readonly /><br /><br />

<input type="button" value="Calculate" onClick="calculate_sum();" />

Now, you have to write the javascript code that takes input from the two input text fields, creates an XML string from input data, gives xml string to backend php code, gets result from PHP, and shows it to the user. Just before the closing head tag “</head>”, enter the javascript code below.

  1. <script language="javascript">

  2. <!--

  3. var cp = new cpaint(); // initializing cpaint object

  4. cp.set_transfer_mode("POST"); // sending data using POST

  5. cp.set_response_type("TEXT"); // recevie data in text form (plain ASCII) as

  6. // opposed to XML object

  7. cp.set_debug(0); // Debug level is 0

  8. function calculate_sum()

  9. {

  10. var first_input = document.getElementById('first_input').value;

  11. var second_input = document.getElementById('second_input').value;

  12. var xml = "<?xml version='1.0' standalone='yes'?>";

  13. xml += "<input>";

  14. xml += "<first>" + first_input + "</first>";

  15. xml += "<second>" + second_input + "</second>";

  16. xml += "</input>";

  17. './', // backend PHP Script Name

  18. 'calculate_sum', // PHP Function Name the data should go to calculate_sum_result, // Javascript callback function

  19. xml // Passing XML String to the backend

  20. );

  21. }

  22. function calculate_sum_result(result) // data returned from PHP is stored in result

  23. {

  24. document.getElementById('result').value = result;

  25. }

  26. //-->

  27. </script>

Lines 1 – 2:

Mark the beginning of Javascript Code.

Lines 3- 7:

Initialize the CPAINT Javascript object, set the transfer mode to POST (you can also use GET), set the response type to TEXT (can also use XML and OBJECT to get XML objects from PHP), and set the debug level to 0 (means no debugging).

Lines 8 – 21:

A new Javascript function that gets called when the user clicks on Calculate button.

On lines 10 - 11 this function extracts data from the two input fields and stores them in two javascript variables. On lines 12 – 16, the function creates an xml string using input data. On lines 17 – 20, calls a function ‘call’ on cp object. takes (i) the backend PHP scrip name as string (ii) backend function name as string (iii) javascript callback function and (iv) xml string as input. It can take more arguments as input (see for more info).

Lines 22 – 25:

Callback function receives the result of calculation from PHP script and prints the result on the read-only result text field.

Now, we have to look at the backend PHP code. You should create another file (recommended) that will be your backend code in PHP. Create an empty PHP file named “”. Add the code below to

  1. <script language="php">

  2. require_once('./'); // require CPAINT PHP Script

  3. $cp = new cpaint(); // Create a new CPAINT Object

  4. $cp->register('calculate_sum'); // register a function to execute

  5. $cp->start(); // start CPAINT

  6. $cp->return_data(); // Return Data

  7. function calculate_sum($xml_str)

  8. {

  9. global $cp; // defines the $cp as global variable

  10. $xml = new SimpleXMLElement($xml_str); // defines a new XML Object

  11. $first = trim($xml->first); // stores the first input number

  12. $second= trim($xml->second); // stores the second input number

  13. $cp->set_data($first + $second); // sets return data to the sum of input numbers

  14. }

  15. </script>

Lines 2 – 6:

CPAINT initialization code, on line 4, I registered the “calculate_sum” function. You have to register all backend functions that you are going to call from javascript with CPAINT using the ‘register’ function, so if you want to register a function named “test_function” you’ll do ‘$cp->register(“test_function”);’ to register the function.

Line 7:

Start of function “calculate_sum” definition. The function also receives the XML string from Javascript in $xml_str.


Declares $cp as global variable inside the function.

Line 10:

Line 10 creates a new XML object using the XML String.

Lines 11 – 12:

Extracts required data from XML object.

Line 13:

Sets return value to the sum of input numbers.

You can of course add some validity checks to the function.


Setting Up Simple Horizontal Menu Bar Using PHPLayersMenu (Part 02)

Add to Technorati Favorites

I have made every attempt to present accurate information, but I cannot guarantee that inaccuracies will not occur. I (the author) will not be held responsible for any claim, loss, damage or inconvenience caused as a result of any information found on this website (blog).

Menu Configuration

You must read Part 01 of this tutorial before reading this.

It is very easy to configure the menu bar and items. You can add or remove menu items in ‘layersmenu-horizontal-1.txt’ but for the look and feel etc. of the menu you have a number of options you can choose from.

Line [1 - 2] - Changing the Menu Bar and Menu Items’ Style:

To change the look and feel of menu bar and items, you can make changes to the CSS stylesheet ‘phplayersmenu/layersmenu-keramik.css’. If you want to use a different style sheet then you have to make changes to the line below. Replace '<new file name with path>' with the new CSS file name.

<link href="<new file name with path>" rel="stylesheet" type="text/css" />

Line [16] - Changing the base directory:

Instead of writing ‘phplayersmenu’ as the base directory name in all functions you can also specify a base folder name $myDirPath = "phplayersmenu".

Lines [19 – 20] - Changing the Images’ Folder/Directory:

You can add more images for arrows by adding new files in 'phplayersmenu/menuimages/'. You can also change the menu images directory by modifying the functions below.

$mid->setImgdir('<new image folder>');

$mid->setImgwww('<new image folder>');

Lines [21 – 22] - Changing the Icons’ Folder/Directory:

The icons’ folder can be changed using the functions below. Replace '<folder name>' with actual folder name below.

$mid->setIcondir('<folder name>');

$mid->setIconwww('<folder name>');

Line [23] - Changing Icon Size:

You can change size of icons used with menu items by making changes to the function parameters of $mid->setIconsize(22, 22);. First parameter denotes width and the second parameter denotes height of icons.

Lines [27 – 28] - Changing Arrows used in Menu Bar:

You can change the arrows (down, forward) using the functions below. Replace '<image file name>' with actual file names.

$mid->setDownArrowImg('<image file name>');

$mid->setForwardArrowImg('<image file name>');

Line [29] - Changing name of Menu File:

Change the name in the function below.


Make sure you delete unnecessary files under phplayersmenu folder. Most of the example scripts are not required on a production server.

Please let me know if you find any errors in this tutorial. Thanks.


Setting Up Simple Horizontal Menu Bar Using PHPLayersMenu (Part 01)

Add to Technorati Favorites

PHPLayersMenu is an easy-to-use, flexible, and advanced Menu System for PHP. With PHPLayerMenu, you don’t have to write your own code to create a menu bar. Moreover, PHPLayersMenu is compatible with many browsers. According to PHPLayersMenu’s home page, it is compatible with the following:

Layers-based menus require JavaScript and work at least on the following browsers:

  • Mozilla 0.6+ (versions 0.9.2+ are suggested)

  • Netscape 6.0+ and other browsers based on Mozilla, e.g. Epiphany and Galeon

  • Konqueror 2.2+ and browsers based on it, e.g. Safari

  • Opera 6.x for Linux

  • Opera 7.x

  • Internet Explorer 5, 5.5, 6.

If old-style templates are used instead of the default ones, layers-based menus work also on the following browsers:

  • Netscape 4.07+

  • Opera 5.x and 6.x

  • Internet Explorer 4

Before we proceed,

DISCLAIMER: I have made every attempt to present accurate information, but I cannot guarantee that inaccuracies will not occur. I (the author) will not be held responsible for any claim, loss, damage or inconvenience caused as a result of any information found on this website (blog).

For this tutorial, I am assuming that the PHP script that uses PHPLayersMenu resides in a folder named ‘test’. Also, I’ll only show how to set up a horizontal Menu bar.

Menu Installation

Follow the steps below:

  • Download PHPLayersMenu from The version that I used for this tutorial is 3.2.0.

  • Extract files from the downloaded file into a folder named “phplayersmenu”.

  • Copy PHPLayersMenu script folder inside the folder ‘ test’.

  • Now, I’ll start off with a simple php page. Name this file “menu.php”. Copy and paste the HTML code below to “menu.php”.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">


<!-- PhpLayersmenu Code Section 01 //-->

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />


<!-- PhpLayersmenu Code Section 02 //-->



<!-- PhpLayersmenu Code Section 03 //-->

<table><tr><td>html code here</td></tr></table>

<!-- PhpLayersmenu Code Section 04 //-->



  • In section 01 of menu.php, copy and paste the code below.

<script language="php">

$myDirPath = "./";

$myWwwPath = "";


  • In section 02 of menu.php, copy and paste code below.

  1. <link href="phplayersmenu/layersmenu-keramik.css" rel="stylesheet" type="text/css"

  2. />

  3. <script language="javascript"

  4. src="phplayersmenu/libjs/layersmenu-browser_detection.js"

  5. type="text/javascript"></script>

  6. <script language="javascript"

  7. src="phplayersmenu/libjs/layersmenu-library.js"

  8. type="text/javascript"></script>

  9. <script language="javascript"

  10. src="phplayersmenu/libjs/layersmenu.js" type="text/javascript"></script>

  11. <script language="php">

  12. include_once("phplayersmenu/lib/PHPLIB.php");

  13. include_once("phplayersmenu/lib/");

  14. include_once("phplayersmenu/lib/");

  15. $mid = new LayersMenu(3, 8, 1, 1);

  16. $mid->setDirroot($myDirPath);

  17. $mid->setLibjsdir('phplayersmenu/libjs/');

  18. $mid->setTpldir('phplayersmenu/templates/');

  19. $mid->setImgdir('phplayersmenu/menuimages/');

  20. $mid->setImgwww('phplayersmenu/menuimages/');

  21. $mid->setIcondir('phplayersmenu/menuicons/');

  22. $mid->setIconwww('phplayersmenu/menuicons/');

  23. $mid->setIconsize(22, 22);

  24. $mid->setTpldir('phplayersmenu/templates/');

  25. $mid->setHorizontalMenuTpl('layersmenu-horizontal_menu-keramik-full.ihtml');

  26. $mid->setSubMenuTpl('layersmenu-sub_menu-keramik.ihtml');

  27. $mid->setDownArrowImg('down-arrow.png');

  28. $mid->setForwardArrowImg('forward-arrow.png');

  29. $mid->setMenuStructureFile('layersmenu-horizontal-1.txt');

  30. $mid->parseStructureForMenu('hormenu1');

  31. $mid->newHorizontalMenu('hormenu1');

  32. $mid->printHeader();

  33. </script>

  • In Section 03 (in menu.php), copy and paste the code below. This is the place where PHP creates the menu bar.

<script language="php">



  • In Section 04 (in menu.php), copy and paste the code below. This should be just above the closing body tag.

<?php $mid->printFooter(); ?>

<script language="javascript" type="text/javascript">


loaded = 1;



  • You also have to create a text file containing the menu items, icons, and links (for more read the files that come with PHPLayersMenu). For now, this file will be named “layersmenu-horizontal-1.txt”. So create a new text file named “layersmenu-horizontal-1.txt” and copy and paste the text below. Items that start with ‘.’ represent top-level menu items and items that start with ‘..’ represent sub menu items. Fields are delimited by the pipe character ‘|’.

.|Menu1||Menu 1 Tag|menu1_icon.png

..|Submenu 1 of Menu 1||Submenu 1 of Menu 1 Tag|submenu_1_1_icon.png

..|Submenu 2 of Menu 1||Submenu 2 of Menu 1 Tag|submenu_2_1_icon.png

.|Menu2||Menu 2 Tag|menu2_icon.png

..|Submenu 1 of Menu 2||Submenu 1 of Menu 2 Tag|submenu_1_2_icon.png

  • Icons must be stored in the directory represented by $mid->setIcondir('’);. The default is ‘phplayersmenu/menuicons/’. So, save all the icon files in this folder.

Upload the Files and folders (phplayersmenu, layersmenu-horizontal-1.txt, and menu.php) and go to menu.php using your favorite browser (must be a supported browser with Javascript Enabled) and go to menu.php. You should see a horizontal layered menu.