Welcome!

Jason Blum

Subscribe to Jason Blum: eMailAlertsEmail Alerts
Get Jason Blum via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: RIA Developer's Journal, AJAX World RIA Conference

RIA & Ajax: Article

Real-World AJAX Book Preview: Creating an AJAX-Friendly Web Service

Real-World AJAX Book Preview: Creating an AJAX-Friendly Web Service

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

Creating an AJAX-Friendly Web Service
For our example Web services, we'll be loosely adhering to the REST principle and creating Web services that are addressable through the service's Uniform Resource Identifier (URI).

Creating a PHP Web Service
This example requires JSON-PHP and assumes you have the XMLRPC extension installed. On Windows ensure that php_xmlrpc.dll is in your extensions folder and edit PHP.INI to uncomment the following line:

;extension=php_xmlrpc.dll

On Unix-based systems you'll have to compile PHP using the --with-xmlrpc[=DIR] configuration option.

In this example we'll create a basic Web service that will return the sum of the digits passed to it. This Web service will be used in the next section with AJAX JSON and XML requests.

The Code

Listing 6.5

<?php
// Only proceed if we were given numbers to sum
if( isset($_GET['numbers']) ) {
   // Split our string into an array using preg_split on any non-digit character.
   $numbers = preg_split("/[^\d]+/", $_GET['numbers']);

   // Force the types of the array values to integer
   array_walk($numbers, create_function('&$elem', 'settype($elem,"integer");') );
   // Set $sum to be the sum of all the digits in our $numbers array
   $sum = array_sum($numbers);

   // Build our response object.
   // We include the original request only to make our response more complex.
   $response = array(
     'numbers' => $numbers,
     'sum' => $sum
   );

   // Check to see if an output format was requested, and if it was JSON
   // Return XML output by default
   if( isset($_GET['output']) && !strcasecmp($_GET['output'], 'json') ) {
     require_once('JSON.php');
     $json = new Services_JSON();
     echo $json->encode($response);
   } else {
     // Send our XML content-type header
     header('Content-type: text/xml');
     // And print out our formatted response
     echo xmlrpc_encode_request(null,$response);
   }
}
?>

Dissecting the Code
This is an extremely simple Web service that can be accessed in a REST-like manner through the resources URI. It expects two variables in the query string: numbers and output. The variable numbers will contain a delimited list of numbers that this Web service will sum and return. To make our return object more complex, we'll return the original request as well as the sum. You can specify your desired output format by setting output to JSON or XML.

A normal GET request to http://yourserver/add.php?numbers=1+2+3&output=json will print the following:

{"numbers":["1","2","3"],"sum":6}

Changing output to XML (http://yourserver/add.php?numbers=1+2+3&output=xml) will return:

Listing 6.6

<?xml version="1.0" encoding="iso-8859-1"?>
  <methodResponse>
   <params>
    <param>
     <value>
      <struct>
       <member>
        <name>numbers</name>
        <value>
         <array>
          <data>
           <value>
            <int>1</int>
           </value>
           <value>
            <int>2</int>
           </value>
           <value>
            <int>3</int>
           </value>
          </data>
         </array>
        </value>
       </member>
       <member>
        <name>sum</name>
        <value>
         <int>6</int>
        </value>
       </member>
      </struct>
     </value>
    </param>
   </params>
  </methodResponse>

You can see that our original response, member name numbers, is there along with the three values we passed it. The second member, sum, has one value, and is the sum of the numbers array.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Corey Gilmore

Corey Gilmore is the president of CFG Consulting, Inc., specializing in developing rich internet applications with ColdFusion, PHP and Ajax for the Federal government and Fortune 100 clients. He guiltily enjoys designing and implementing low-cost, high performance business continuity plans using VMware ESX server. As the former Director of Information Technology for the United States Senate Democratic Leadership, he designed and implemented a continuity of operations plan to ensure Senate business continuity in the event of a disaster. Corey can be reached at cfgci.com.

More Stories By Jason Blum

Jason Blum is principal engineer with the advanced technologies development team in the United States Senate, Office of the Sergeant at Arms. Formerly the lead administrator of the Senate’s shared Web hosting environment, Jason now designs and manages the implementation of schema and pattern-centric solutions for Senate offices in XML, ColdFusion, Flex, and .NET. He is a Certified Advanced ColdFusion developer with a BA in philosophy, Masters Degrees in philosophy of education and in IT, and an intermediate certification in Hungarian from itk.hu.

More Stories By Phil McCarthy

Philip McCarthy is a UK-based software development consultant
specializing in J2EE and Web technologies. An early adopter of rich
browser-based client development, he has several years' experience of integrating Ajax technologies into enterprise Java frameworks, gained on projects in the financial services, telecoms, and digital media sectors. Philip is also the author of the "Ajax for Java Developers" series for IBM developerWorks, and blogs about software development at chimpen.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.