Creating Web Apps using CPAINT AJAX Framework (PART I) - Example
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).
Installation:
Follow the steps below:
- Fire up your web browser and go to cpaint.sourceforge.net. 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
- cpaint2.inc.php
- cpaint2.inc.compressed.js
- 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="./cpaint2.inc.compressed.js" 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.
- <script language="javascript">
- <!--
- var cp = new cpaint(); // initializing cpaint object
- cp.set_transfer_mode("POST"); // sending data using POST
- cp.set_response_type("TEXT"); // recevie data in text form (plain ASCII) as
- // opposed to XML object
- cp.set_debug(0); // Debug level is 0
- function calculate_sum()
- {
- var first_input = document.getElementById('first_input').value;
- var second_input = document.getElementById('second_input').value;
- var xml = "<?xml version='1.0' standalone='yes'?>";
- xml += "<input>";
- xml += "<first>" + first_input + "</first>";
- xml += "<second>" + second_input + "</second>";
- xml += "</input>";
- cp.call( './backend.inc.php', // backend PHP Script Name
- 'calculate_sum', // PHP Function Name the data should go to calculate_sum_result, // Javascript callback function
- xml // Passing XML String to the backend
- );
- }
- function calculate_sum_result(result) // data returned from PHP is stored in result
- {
- document.getElementById('result').value = result;
- }
- //-->
- </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. cp.call 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 http://cpaint.sourceforge.net/doc/frontend.class.cpaint.call.html 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 “backend.inc.php”. Add the code below to backend.inc.php.
- <script language="php">
- require_once('./cpaint2.inc.php'); // require CPAINT PHP Script
- $cp = new cpaint(); // Create a new CPAINT Object
- $cp->register('calculate_sum'); // register a function to execute
- $cp->start(); // start CPAINT
- $cp->return_data(); // Return Data
- function calculate_sum($xml_str)
- {
- global $cp; // defines the $cp as global variable
- $xml = new SimpleXMLElement($xml_str); // defines a new XML Object
- $first = trim($xml->first); // stores the first input number
- $second= trim($xml->second); // stores the second input number
- $cp->set_data($first + $second); // sets return data to the sum of input numbers
- }
- </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.
Line9:
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.
Labels: ajax php CPAINT example easy calculator backend javascript xml tutorial
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home