Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Consuming PHP Web Services with AJAX  : Page 3

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


advertisement

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 <div> 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):

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> <title>Web Service SOAP and AJAX</title> </head> <script type="text/javascript" src="./ajaxSOAP.js"></script> <body> <div style="position:relative;left:0px; top:-12px;background-color:#1D3968;margin:0px;"> <h2 align="center"><font color="#ffffff"> Consume WebServices through SOAP-AJAX calls</font></h2></div> <table align="center" cellpading="0px" cellspacing="3px" bordercolor="#000000" border="0" style="position:relative;width:300px;height:200px;"> <tr> <td colspan="2" align="center"><h1>Rectangle Area</h1></td> </tr> <tr> <td valign="center"><font color="#cc0000" size="3"> Insert value for l:</font></td> <td><input id="l_id" type="text"></td> </tr> <tr> <td><font color="#cc0000" size="3">Insert value for L:</font></td> <td><input id="L_id" type="text"></td> </tr> <tr> <td><input type="button" value="Calculate Area" onclick="myAjax();"></td> </tr> <tr> <td colspan="2"> <div id="resultDiv"></div> </td> </tr> </table> </body> </html>

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 = ' <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:mathwsdl"> <SOAP-ENV:Body> <tns:RectangleArea xmlns:tns="urn:mathwsdl"> <L xsi:type="xsd:int">' +L_var+'</L> <l xsi:type="xsd:int">'+l_var+'</l> </tns:RectangleArea> </SOAP-ENV:Body> </SOAP-ENV:Envelope>';

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"); } httpRequest.open("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.

httpRequest.send(soapMessage);

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"); resultDiv.style.display='inline'; resultDiv.innerHTML='<font color="#cc0000" size="4"><b>'+httpRequest.responseText+'</b></font>'; } } } 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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

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