RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Consuming PHP Web Services with AJAX

Discover how to write PHP web services and consume them through SOAP-AJAX calls.

mong other things, in this article you'll see how to write a PHP web service using the NuSOAP library, as well as a JavaScript client to consume it using the AJAX technology and the SOAP protocol. But first, you need a small dollop of web services terminology.

Short Overview of SOAP and Web Services

SOAP, which stands for "Simple Object Access Protocol," is an XML-based request/response messaging protocol. One important characteristic of SOAP is that it's independent of any transport protocol (HTTP is the most frequently used, but you can use SMTP, MIME, and so on), operating system, or programming language. This makes it very flexible over different software architectures-and also very easy to use.

A web service is a generic description of a software system designed to be called remotely over a network. The services offered can cover many tasks, and the implementation may vary, but a typical web service assumes that:

  • A web service is exposed as a server that can be interrogated based on a set of operations.
  • It "publishes" available operations using an XML document known as a WSDL (Web Services Description Language) document. Normally, this document is both generated and parsed (interpreted) by machines, not by humans.
  • Entities that access the web services are known as web service clients.
  • The communications protocol between clients and servers is SOAP.

Using SOAP in PHP

Because web services quickly became a widely used technology, every popular programming language sought to develop and improve their support for creating and exploiting web services. For example, PHP has a few extensions (PEARs and libraries) that add web services support. Starting with PHP5, such support ships with the language in a library called NuSOAP.

Because the NuSOAP library has a great usability/performance rate you'll see how to use it in this article to develop a complete web service. If you're more familiar with other extensions/libraries and you are interested only in the second portion of the article—how to develop the JavaScript AJAX client, you can of course rewrite the server-side web service using any technology you choose.

The NuSOAP library is a collection of PHP classes that supports sending and receiving SOAP messages using the HTTP protocol. The NuSOAP library, also known as "SOAPx4," is a NuSphere product; you can download it here. To make your PHP source files aware of NuSOAP classes, include the following code snippet:

   require_once('{NuSOAP folder path and name}/lib/nusoap.php');
The server you'll develop with NuSOAP exposes two methods, named TriangleArea and RectangleArea. As the names suggest, these methods calculate the area of a triangle and of a rectangle, respectively. Here's the procedure for developing the web service.

  1. First, write the two methods—a simple task, as you can see:
  2.    // Define the TriangleArea method as a PHP function
       function TriangleArea($b, $h) {
          return 'The triangle area is: ' .((b*h)/2);
       // Define the RectangleArea method as a PHP function
       function RectangleArea($L, $l) {
          return 'The rectangle area is: ' .($L*$l);
Each method takes two parameters: integer values for the base and height of the triangle for the TriangleArea method, and the width and height of a rectangle for the RectangleArea method and returns a string that contains a value for the calculated area.

With the two methods in place, you need a web service to expose them.

  1. Because NuSOAP encapsulates the details of a web service under a single class, you can obtain a web service instance by calling the soap_server empty constructor, like this:
  2.    // Create the server instance
       $server = new soap_server();
  3. Provide a name and namespace for the WSDL file that corresponds to your web service server. You do this by calling the configureWSDL method of the nusoap.php class, which requires only a name and a namespace:
  4.    // Initialize WSDL support
       $server->configureWSDL('mathwsdl', 'urn:mathwsdl');
  5. Next, register the methods (two in this example). Registering a method makes the web service server aware of the method's name, arguments, return type, SOAP action, style, encoding and description. You can specify all these properties via a single method, named register. For example, you can register the TriangleArea and RectangleArea methods as follows:
  6.     // Register the TriangleArea method 
       $server->register('TriangleArea',                  // method name
           array('b' => 'xsd:int', 'h' => 'xsd:int'),     // input parameters
           array('area_t' => 'xsd:string'),               // output parameters
           'urn:mathwsdl',                                // namespace
           'urn:mathwsdl#TriangleArea',                   // soapaction
           'rpc',                                         // style
           'encoded',                                     // use
           'Calculate a triangle area as (b*h)/2'         // documentation
       // Register the RectangleArea method to expose
       $server->register('RectangleArea',                 // method name
           array('L' => 'xsd:int', 'l' => 'xsd:int'),     // input parameters
           array('area_r' => 'xsd:string'),               // output parameters
           'urn:mathwsdl',                                // namespace
           'urn:RectangleAreawsdl#RectangleArea',         // soapaction
           'rpc',                                         // style
           'encoded',                                     // use
           'Calculate a rectangle area as (L*l)'          // documentation
The preceding registration is specific to NuSOAP.

  1. Finally, to invoke the web service, call the NuSOAP service method as follows:
  2.     // Use the request to (try to) invoke the service
         isset($HTTP_RAW_POST_DATA) ? 
         $HTTP_RAW_POST_DATA : '';
Putting together everything described in the five simple steps above, you get code similar to the web service server in Listing 1 (save it in a folder named webservice).

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date