Three Ways to Consume Web Services with AJAX
 
Published: 26 Apr 2007
Abstract
This article examines the different ways that web services can be consumed using AJAX.
by Xianzhong Zhu
Feedback
Average Rating: 
Views (Total / Last 10 Days): 65931/ 68

Introduction

In recent months, AJAX has become more and more heated. How Web Service, the commonly accepted way to supply business logic, can be consumed via AJAX naturally attracts the attention of so many AJAX enabled solution providers as well as developers. In this article I will show you three different ways to consume Web Services using simple yet integral samples.

Requirements

·         Windows XP Professional (with IIS installed)

·         Visual Studio 2005

·         SOAP-based JavaScript library titled soapclient.js

·         AjaxPro.NET Framework

·         Microsoft ASP.NET AJAX Framework

To follow along with the examples, you need to download the source files accompanying this article. And also, for brevity, we omit representing the install of each framework used below since each is shipped with a straightforward introduction.

Consume Web Services the straight way—through XMLHttpRequest object

As is well known, Web Services can be accessed via the HTTP-based protocol. The great objectXMLHttpRequest, therefore, may be used directly to call Web Services. According to the features of XMLHttpRequest and Web Services and what the client side needs, the whole process can be divided into three detailed steps.

·         Send the HTTP requests to Web Services via XMLHttpRequest and get the corresponding HTTP responses.

·         Resolve the XML data returned from the server and pick out the needed data.

·         Render the acquired data via the client-side JavaScript.

No doubt that the difficulty lies in Step 2resolving XML in the client side. In this aspect, different browsers have offered different solutions. In Microsoft Internet Explorer, we can achieve our goal by resorting to the ActiveX controlXMLDOM. As for other browsers, such as Mozilla's FireFox, Opera, etc., the third-party script libraries are often borrowed in order to resolve XML data. For example, Google's google ajaxslt can resolve XML and convert XSLT.

Joyfully, to obtain the required data from the XML object returned via Web Services does not need to resolve XML completely. Thus, besides the HTTP protocol scheme, we can use SOAP (Simple Object Access Protocol) to call a Web Service, such as the SOAP-based JavaScript librarysoapclient.js. This library can be downloaded from www.guru4.net and the accompanied source codes in this article also provide one. Figure 1 gives us the general depiction of this small framework.

Figure 1: The mechanism of calling web services provided by soapclient.js

This script is so direct and simple to use that we only give a corresponding sample.

First, define the Web service as usual.

Listing 1

[WebMethod]
Public string HelloWorld()
{
  Return "Hello World!";
}

Next, write the client-side JavaScript to call the Web service.

Listing 2

function HelloWorld()
{
  var pl =new SOAPClientParameters();
  SOAPClient.invoke(url, "Hello World", pl, true, HelloWorld_callback);
}
function HelloWorld_callback(r)
{
  alert(r);
}

Here, we only illustrate an ABC example; for more complicated ones please refer to the related web site.

The AjaxPro.NET based approach

Thanks to Microsoft we can easily access a web service from inside an ASP.NET 2.0 framework. So, we can first invoke web services in the methods inside an ASP.NET 2.0 page and in turn call these methods via the open-source Ajax frameworkAjaxPro.NET. Figure 2 gives you a more illustrative explanation.

Figure 2: Call Web Services via AjaxPro.NET framework

Now, let us take a further look at the famous framework.

A brief introduction to AjaxPro.NET

AjaxPro.NET is a well-known open source framework, which is based on the server-side techniques in support of different versions of ASP.NET web applications. The framework can create proxy classes on client-side JavaScript to invoke methods on the web server with full data type support working on all common web browsers, including mobile devices. One of the most worthy features of this framework is that it supplies a developer with only one method for call and, therefore, dramatically increases the productivity effect.

Since the downloaded materials have been shipped with a guide and an excellent Visual Studio Add-in (named 'AjaxProVSTemplate.vsi'), we do not dwell on its details here, but make room for the following sample. For another basic usage of AjaxPro.NET, you can refer to my old article Building an AJAX Based Web Chatting Application using ASP.NET 2.0.

Sample 1

To achieve our goal in this article, you should keep to the following steps.

·         Add the reference to AjaxPro.2.dll (automatically done by the template).

·         Register the page for AjaxPro.2.dll using AjaxPro.Utility.RegisterTypeForAjax(typeof(Namespace.class)).

·         Create a web service to be called using the Ajax method.

·         Add the specific attribute to the method with [AjaxPro.AjaxMethod].

·         Add the JavaScript function to call the method.

·         Create the call back function to deal with the returned data.

1. Create an AjaxPro.NET-Enabled sample Web Site

Launch Visual Studio 2005 and then select menu "File | New Website…." In the subsequent "New Website" dialog select the template named "Ajax.NET Professional Web Site" and name the project AjaxPro2Service, as well as choose Visual C# as the built-in language.

Next, modify page Default.aspx as illustrated in Figure 3 (here we give the runtime snapshot).

Figure 3: Call Web Services via Ajaxpro.NET framework

When you enter the name of the car producer (and optional car model) and the year, you will see an alert box with the current price of the car.

2. Create a Web Service

Right click the project and choose "Add new item." In the "Add new item" dialog box select Web Service and name the service CarService.asmx.

Open file CarService.cs and add a WebMethod named getCarValue (see Listing 3).

Listing 3

public class CarService: System.Web.Services.WebService
{
  [WebMethod]
  public int getCarValue(string strCarMake, string strCarModel, int strCarYear)
  {
    int nReturn = 0;
    if (strCarMake == "Honda")
      nReturn = 30000;
    else
      nReturn = 20000;
    if (strCarModel == "Pilot")
      nReturn += 10000;
    int nDepreciation = (System.DateTime.Now.Year - strCarYear) * 2000;
    nReturn = nReturn - nDepreciation;
    return nReturn;
  }
}

Here, WebMethod getCarValue can figure out the price of the given type of car.

3. Create an Ajax method to call the Web Service

According to the analysis above, we can create an AjaxPro.NET-styled method to call the web service defined in step 2.

Listing 4

[AjaxPro.AjaxNamespace("AjaxExamples")]
public partial class _DefaultCS: System.Web.UI.Page
{
  [AjaxPro.AjaxMethod]
  public int getCarValue(string make, string model, int year)
  {
    ServiceSpace.CarService newCar = new ServiceSpace.CarService();
    int v = newCar.getCarValue(make, model, year);
    return v;
  }
  protected void Page_Load(object sender, EventArgs e)
  {
    // Register Ajax.NET methods from this class
    AjaxPro.Utility.RegisterTypeForAjax(typeof(_DefaultCS));
  }
}

There' is nothing special to be emphasized here except for the simple formula-like coding based on the framework.

4. Call Ajax methods from client side

Now comes the last stepcalling the Ajax method defined above from the client side. When you click the button Get Value in Figure 2, the browser will invoke its event handler as in Listing 5.

Listing 5

function btnGetValue_onclick()
{
  AjaxExamples.getCarValue(document.getElementById("txtMake").value,
    document.getElementById("txtModel").value, document.getElementById(
    "txtYear").value, getCarValue_callback);
}
 
//callback we told AjaxPro.Net to pass the response to
function getCarValue_callback(response)
{
//if the server side code threw an exception
  if (response.error != null)
  {
    alert("The server side error! Maybe your input is out of scope." +
      response.error);
    return ;
  }
  var price = response.value;
// take the corresponding action
// according to the type of 'response'
  alert(price);
}

For now you are ready to run the sample. Press F5 and you will see the screen like Figure 2. As for the data you should enter, please refer to the definition of WebMethod getCarValue.

Access Web Services the Microsoft way—through ASP.NET AJAX 1.0 Framework

Now, let us look into the Microsoft way of consuming Web Services with AJAX.

About ASP.NET AJAX 1.0

ASP.NET AJAX (formerly referred to as "Atlas") was an add-on to ASP.NET 2.0, with the goal of aiding developers in creating more interactive AJAX-enabled Web applications. The framework includes two distinct yet not mutually exclusive API's: client and server, which enable the developers to accomplish AJAX functionalities using direct client-side programming, traditional server-side programming, or any combination of both. Figure 4 shows the client architecture of the asynchronous communication layer of this framework.

Figure 4: Client-side architecture of ASP.NET AJAX framework

The client architecture contains two main groups: the communication group and the support group. The communication group contains client script that performs Web services communication between the client and the server. Note that Web request handling is intrinsically an asynchronous process. The communication group is based on the browser’s XMLHTTP object and on executor objects that dispatch browser requests to the Web service. In Microsoft ASP.NET AJAX, the asynchronous communication layer generates client-script proxy classes automatically. You can then use the JavaScript proxy objects to make asynchronous requests to the server from client script. There are two possible approaches to making a Web service request:

·         Calling Web services by using the HTTP POST verb. In this way, there is not a size limitation. Therefore, you can use a POST request when the size of the data exceeds the intrinsic size limitation for a GET request. The client serializes the request into JSON format and sends it as POST data to the server. The server deserializes the JSON data into .NET types and makes the actual Web service call. During the response, the server serializes the return values and passes them back to the client, which deserializes them into JavaScript objects for processing.

·         Calling Web services by using the HTTP GET verb. This resembles the functionality of a POST request, with the following differences:

          1. The client uses a query string to send the parameters to the server.

          2. A GET request can call only a Web service method that is configured by using the [ScriptMethod(UseHttpGet = true)] attribute.

          3. Data size is limited to the URL length allowed by the browser.

Author's Notes: ASP.NET AJAX's web services layer, by default, does not allow web methods to be invoked via the HTTP GET verb in order to prevent it from being susceptible to various types of JSON hijacking attacks. So, to make an ASP.NET AJAX web-method callable via HTTP GET-access, a developer must explicitly attribute each method using ASP.NET's ScriptMethod attribute (and set the UseHttpGet property to true).

Since our main attention is focusing on how to call web services with AJAX, we only give you the framework's server architecture of the asynchronous communication layer.

Figure 5: Server-side architecture of ASP.NET AJAX framework

Enough of theory debate—let us get into some code!

Sample 2

1. Create an ASP.NET AJAX-Enabled sample Web Site

Again, launch Visual Studio 2005 and then select menu item "File | New Website…" to create a new website using the template named "ASP.NET AJAX-Enabled Web Site " and name the project WebServiceTest (again select Visual C# as the built-in language).

Next, with a little modification, page Default.aspx finally looks like Figure 6.

Figure 6: The design-time sample web page for Sample 2

Notice that as soon as the wizard ends there is automatically added a ScriptManager server control. This server control acts as the center of whole ASP.NET AJAX 1.0 framework, taking charge of management and scheduling of various JavaScript libraries used by the client-side runtime. Here, for the purpose of testing to call Web Services from inside client-side JavaScript, we drop a HTML Input Button onto the page, as well as three HTML Input Text controls.

2. Create a Web Service

Next, we will write a web service to be accessed via the browser JavaScript. Here, only for illustration, we let the service calculate the sum of two integers.

Right click the project and choose "Add new item" and create a new Web Service named SumService.asmx. Next, we are going to open file SumService.cs and create our own WebMethodGetSum.

According to the framework, we must put the attribute ScriptService before the Web Service so as for JavaScript to call it. Listing 6 gives the crucial code snippet.

Listing 6

using System.Web.Services.Protocols;
using System.Web.Script.Services;
 
namespace SumServiceSpace
{
  [ScriptService]
  public class SumService: System.Web.Services.WebService
  {
    [WebMethod]
    //[ScriptMethod(UseHttpGet = true)]
    public int GetSum(int a, int b)
    {
      return (a + b);
    }
  }
 
}

Here, WebMethod GetSum is to calculate the sum of two given integers.

Author's Notes: The Microsoft AJAX Library enables client script and the Web service to exchange complex types. In this sample, we only consider the simple one. For details, please see the online tutorial (ajax.asp.net).

3. Consume the Web Service

Now we get to the really interesting thing. Please switch to the Design View of page Default.aspx and click control ScriptManager1. Next, click the "…" on the right side of attribute Services in the Property window and enter into the dialog box, operating in the sequence as Figure 7 shows.

Figure 7: declaratively programming the control ScriptManager from the Property dialog box

OK, the last related source code looks like the code below.

Listing 7

<asp:ScriptManager ID="ScriptManager1" runat="server" >
  <Services>
   <asp:ServiceReference Path="SumService.asmx" />
  </Services>
</asp:ScriptManager>

Here, we have created an instance of ServiceReference with attribute Path pointing to the service file SumService.asmx in the declarative way.

Finally, we are to code how to call the web service proxy with the values of the two TextBox controls passed to it. Double click the Get the sum via a Web Service button in Figure 5 above and add the following into the event handler.

Listing 8

function btnSum_onclick()
{
  SumServiceSpace.SumService.set_defaultSucceededCallback(OnSuccess);
 
  SumServiceSpace.SumService.GetSum(eval(form1.TextBoxA.value), eval
    (form1.TextBoxB.value), OnSuccess());
 
}
 
function OnSuccess(result)
{
  $get("TextBoxSum").value = result;
}

Here, the most important thing to be noticed is that calling a Web service method from script is asynchronous. As the framework says, to get a return value or to determine when the request has returned, you must provide a callback function. The callback function is invoked when the request has finished successfully. The function exposes the return value. So, OnSuccess here corresponds to the callback functionall the manipulation with the values post back from the web service's methods is done herein. Another important thing to notice is method GetSum is passed into three arguments (in fact there' is still one omitted here) while the one defined in the Web Service merely takes two! Why? This extra parameter represents the name of the callback function as a pointer to the function called when the service invocation succeeds (the other omitted one corresponds to the function called when the service invocation fails or overtime). Apparently, this calling approach hides the asynchronous feature of AJAX (have we associated this with the mechanism and usage of the great many callbacks with Win32 API?).

Still, one thing to be emphasized is whether the call is successful or not; web methods defined in the Web Service should return a value contained in the parameter result of the callback. In this scenario, for each successful request/response the parameter result contains the sum of two given integers. By the way, $get("TextBoxSum") corresponds to the commonly used document.getElementById("TextBoxSum") in DOM programming, which is simplified by the ASP.NET Ajax framework.

4. Running the sample and Troubleshooting

Without any trouble, press F5 and you will see the runtime screenshot like Figure 8.

Figure 8: The runtime screenshot of Sample 2

Subtle readers may notice that after you have entered two integers in the TextBoxes above and press the Get the sum via a Web Service button, there will appear a strange string'Undefined' before you get the correct result6912. Regrettably, I have not found the why for now, so sincerely welcome anyone who can help me with the trouble.

Comparison

Today, it has been estimated that more than 100 frameworks for AJAX development exist, which are in support of a variety of platforms and utilize a number of programming approaches. In general, however, they can be grouped into three main categories based on their capabilities: callback frameworks, UI frameworks, and full frameworks. The first two solutions in this article should fall into the first category (but AjaxPro.NET is the stronger and the favorite one to be used by developers by virtue of its simplicity and other more stability), while ASP.NET AJAX belongs to the third one with a package of client/server-side AJAX related projects.

Here, for brevity and for our interesting topic concentrating on Web Services, we have set up a table (Table 1) to give a synopsis of comparison of the three frameworks discussed in this article.

Table 1: Comparison of the three Ajax-enabled frameworks

Framework

Features

Callback support

UI

support

Full support

Others

soapclient.js

X

 

 

 

AjaxPro.NET

X

 

 

Access the Session and Application data from the client-side JavaScript

Cache the required results

Freely use source code

Add and modify new methods and properties in the framework without modifying any source code

All the classes support the client-side JavaScript to return data, and DataSet can be used from inside the JavaScript

Use the HTML controls to access and return data

Do not need to reload the pages and use the event delegate to access data

Supply only one method for call and therefore dramatically increases system performance

Microsoft ASP.NET AJAX

X

X

X

OOP JavaScript programming

JSON support

Debug/Trace support

Safety support

support for batching

WCF service support

Browser compatibility (IE, Firefox, Safari)

To be honest, I am not well up in the three frameworks either, so please forgive me for the shallow comparison above.

Downloads

Summary

Web Services often bear responsibility of the tier of business logic in the web application development. As far as various AJAX solutions are concerned, there exists the similar requirement. In this article, we have only examined three seemingly distinct yet relative solutions of consuming Web Services in the AJAX way with three basic samples. Nearly two years have passed since the great "AJAX" dazzled people's eyes. Maybe, the great Web 2.0 eve has just begun; so there is too much for us to explore, as well as the famous Web Services.



User Comments

Title: Sr. Web Developer   
Name: Nelson Xu
Date: 2008-09-04 11:20:30 AM
Comment:
Hi Xianzhong,
I reall enjoy your article and code sample.
The reason that "Undefined" appears is because you have () for OnSuccess when you call Web service.

SumServiceSpace.SumService.GetSum(
eval(form1.TextBoxA.value),
eval(form1.TextBoxB.value),
OnSuccess());

Message will go away if you remove () after OnSuccess.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 4:12:02 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search