Consuming PHP Web Services with AJAX

Consuming PHP Web Services with AJAX

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.
See also  Strengthening Business Cybersecurity With Threat Intelligence

  1. Finally, to invoke the web service, call the NuSOAP service method as follows:
  2.     // Use the request to (try to) invoke the service   $HTTP_RAW_POST_DATA =      isset($HTTP_RAW_POST_DATA) ?      $HTTP_RAW_POST_DATA : '';   $server->service($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).

Verifying Web Services

One nice feature of NuSOAP is that it lets you verify that a web service exists and ensure that it exposes the methods you need—without having to develop a client. For example, accessing the URL http://localhost/php/webservice/nusoap_server.php link reveals the web service WSDL for the web service you just created (note that you didn’t have to write or generate a WSDL—but the WSDL is there, nonetheless), and the service methods. Next to each method name you can see a list containing the information you need to write a proper web service client. Figure 1 shows a screen capture of the WSDL and methods for the nusoap_server.php sample web service.

Figure 1. Verifying Web Services: Accessing the web service URL reveals the WSDL file and the service methods.

Writing a Web Service Client

With the server completed and verified, you can write a NuSOAP web service client. This is a process even simpler than creating a server, as you will see in this section. The steps are:

  1. Start by creating a client instance by instantiating the soapclientNusoap class. Typically, you will use the class constructor that takes the WSDL URL and a Boolean value indicating that you want to use a WSDL file (NuSOAP also lets you create web services without WSDLs, but that aspect is not discussed here).
  2.    // Create the client instance   $client = new soapclientNusoap(      'http://localhost/php/webservice/nusoap_server.php?wsdl', true);
  3. It’s best practice to check for errors at this point, for example:
  4.    // Check for an error   $err = $client->getError();   if ($err) {      // Display the error      echo '

    Constructor error

    ' . $err . '

    '; // At this point, you know any calls to // this web service's methods will fail }

  5. Finally, you can call the web service methods using the NuSOAP call method. The following examples call the TriangleArea and RectangleArea methods (notice that they also check for potential errors).
  6.    // Call the TriangleArea SOAP method   $result = $client->call('TriangleArea',       array('b' => 10, 'h' => 15));      // Check for a fault   if ($client->fault) {       echo '


    ';       print_r($result);       echo '

    '; } else { // Check for errors $err = $client->getError(); if ($err) { // Display the error echo '


    ' . $err . '

    '; } else { // Display the result echo '


    ';           print_r($result);       echo '

    '; } } // Call the RectangleArea SOAP method $result = $client->call('RectangleArea', array('L' => 40, 'l' => 20)); // Check for a fault if ($client->fault) { echo '


    ';       print_r($result);       echo '

    '; } else { // Check for errors $err = $client->getError(); if ($err) { // Display the error echo '


    ' . $err . '

    '; } else { // Display the result echo '


    ';           print_r($result);       echo '

    '; } }

    Figure 2. Web Service Client: Browsing to the nusoap_client.php client page shows the results of the TriangleArea and RectangleArea calls made from that page as well as the request and response details.
  7. Optionally, you can display the requests/responses like this:
   // Display the request and response   echo '


'; echo '
' . htmlspecialchars($client->request,       ENT_QUOTES) . '

'; echo '


'; echo '

' . htmlspecialchars($client->response,       ENT_QUOTES) . '

';When you put the four steps described above together to create a web service client, the results will look like Listing 2 (save the code in Listing 2 to the webservice folder):

Now, you can test your first NuSOAP web service by opening the http://localhost/php/webservice/nusoap_client.php URL in a browser. The output should look like Figure 2.

At this point, you’ve built a web service, exposed its methods, and consumed it on the server using PHP code. The next section discusses how to consume a web service from a JavaScript AJAX client.

Write a JavaScript Web Service Client

This section describes how to create a browser web service client in JavaScript that uses AJAX technologies for the RectangleArea method (calling the TriangleArea method is essentially the same).

You start by writing a simple HTML interface that lets a user specify values for the width and height arguments of the RectangleArea method. You pass the entered values to a JavaScript function named myAjax, which will reside in a separate JavaScript module named ajaxSOAP.js. This HTML will contain an empty

tag that AJAX will fill with the response received from the web service server. Here’s a minimal interface (save it in the webservice folder):

                      Web Service SOAP and AJAX                             

Consume WebServices through SOAP-AJAX calls

Rectangle Area

Insert value for l:
Insert value for L:

The preceding code doesn’t offer an implementation for the myAJAX function, but don’t worry, because you’ll do that next. Start by creating an empty JavaScript module and name it ajaxSOAP.js. Save this module in the same webservice folder as the preceding HTML code.

The MyAJAX function begins by extracting the arguments that must be passed to the web service server. Remember that users provide the argument’s values through the HTML interface, so you have to access the two text fields identified by the IDs l_id and L_id:

       var l_var = document.getElementById("l_id").value;       var L_var = document.getElementById("L_id").value;

After obtaining the argument’s values you need to write the SOAP message. This simple SOAP message calls the RectangleArea method, passing it the two values that the service needs to calculate the area. For now, you’ll store the SOAP message into a JavaScript variable:

   soapMessage = '                                         ' +L_var+'            '+l_var+'                        ';

Next, implement the AJAX mechanism. Following a typical approach, you start by obtaining an XMLHttpRequest object, and continue by opening a POST channel on the server’s URL (http://localhost/php/webservice/nusoap_server.php), indicating the AJAX callback function, named callbackAjax.

   if(window.XMLHttpRequest) {      httpRequest=new XMLHttpRequest();   }   else if (window.ActiveXObject) {       httpRequest=new ActiveXObject("Microsoft.XMLHTTP");    }"POST",url,true);   if (httpRequest.overrideMimeType) {       httpRequest.overrideMimeType("text/xml");    }   httpRequest.onreadystatechange=callbackAjax;

The next three lines of code are not commonly used in AJAX implementations; they represent three HTML headers that will make an important contribution to the success of calling the web service. You should particularly remember to provide the MessageType header, which indicates that the message contains a call—a SOAP request.

   httpRequest.setRequestHeader("Man", "POST       http://localhost/php/webservice/nusoap_server.php HTTP/1.1")             httpRequest.setRequestHeader("MessageType", "CALL");      httpRequest.setRequestHeader("Content-Type", "text/xml");

Finally, you send the SOAP request and wait for the response.


That completes the request side of the AJAX mechanism. You implement the response side in a traditional manner, as you will see in the following code. The callbackAjax function below retrieves the web service response, adds some formatting, and displays the results in the resultDiv

tag you created in the HTML. Note that the response is also a SOAP message, but most browsers will know how to parse it and extract only the payload (the useful information). However, if you’re working with a web service and you get a response that contains chunks of SOAP XML, the solution is to implement a SOAP message parser (by extracting the response using the responseXML property, instead of responseText, and then using the XML DOM Parser to extract just the information you need).

   function callbackAjax(){      try {         if(httpRequest.readyState==4) {            if(httpRequest.status==200) {              clearTimeout(xhrTimeout);                                                                           resultDiv=document.getElementById("resultDiv");                'inline';                                                        resultDiv.innerHTML=''+httpRequest.responseText+'';            }         }       } catch(e) {            alert("Error!"+e);       }         }

Listing 3 shows the complete code for the ajaxSOAP.js module.

Author’s Note: At the top of Listing 3, the xhrTimeout variable and the ajaxTimeout function are optional—they simply increase the robustness of your AJAX code by stopping the callback mechanism if the request/response time exceeds 120,000 milliseconds, which should allow more than enough time for a response. If that happens, you might want to inform the client that something is wrong; perhaps the server crashed, or the connection is unavailable, etc.

Testing the JavaScript/AJAX Client

Now for the fun part: testing the JavaScript/AJAX client. Open your browser and browse to the http://localhost/php/webservice/ URL. You should see something similar to Figure 3.

Figure 3. Testing the JavaScript/AJAX Client: Using the client interface, you can enter rectangle width and height values and get the area.

Insert two integers in the two text fields (For example, type 40 for l and 120 for L) and press the Calculate Area button. You should get something like Figure 4.

Figure 4. Rectangle Area: When you enter two integer values and press the Calculate Area button, you’ll see the area result appear below the button.

Monitoring the SOAP request-response mechanism

If you want to see the HTML headers and SOAP messages sent behind the scenes, there are dedicated applications available. One simple approach uses “Firebug,” a free plug-in for Firefox. For example, Figure 5 shows the HTML request/response headers that were sent and received by the AJAX client to the nusoap_server.php web service:

Figure 5. HTML Headers: Here’s a partial view of the headers posted to the web service.

Similarly, you can monitor the complete SOAP request (see Figure 6), and response (see Figure 7)

Figure 6. SOAP Request: Here’s the raw SOAP message posted to the web service.
Figure 7. SOAP Response: Here’s the raw SOAP response from the web service.

Calling web services from AJAX is an interesting and natural approach, considering that web services typically respond with string messages, numbers, or images in various formats (such as SVG), while developers typically use AJAX in web pages to retrieve and display strings, numbers, and images—exactly the same kind of information. Putting the two together is a good technique that will help you build cool interactive web sites.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist