Calling Web Services Using AJAX

By Jonathan Wood on 4/15/2012
Language: C#JavaScript
Technology: AJAXjQueryWebForms
Platform: Windows
License: CPOL
Views: 19,939
Web Development » Client Scripting » AJAX » Calling Web Services Using AJAX

Demo Program Screenshot

Download Demo Project Source Download Demo Project Source


In this article, I will present an ASP.NET WebForms application that will submit data to the server and get a response, all without refreshing the current page. We will accomplish this by making an AJAX call to a web service using jQuery.

This can be quite useful for providing functionality with a good user experience. For example, let's say you have a web page that allows the user to cast a vote for some content. The user may click on a button or icon, but they don't necessarily want to leave the current page. We may want to record the user's action using client-side script to contact the server while the user is still viewing the same page. In addition, we may want to get a response back from the server so that we can use client script to alert the user if anything went wrong. Again, while the user is still viewing the same page.

For the code I'll present, we'll accomplish this by calling a web service. The web service will be passed an argument so that it can accomplish a task on the server, which may involve updating a database, etc. And the web service will return a response that can be examined from client-side script.

I should point out that ASP.NET WebForms provide you with Web Controls that can make AJAX calls easier. However, they are not ideal for all situations. The AJAX controls can be rather "heavy" and don't provide that much flexibility. Besides, once you learn how to make AJAX calls without using the AJAX Web Controls, it really isn't that much more work anyway.

Writing the Web Service

Listing 1 shows my ProcessItem() web service. This is a very simple web service to demonstrate the technique I'm using. It accepts a single integer argument and considers the call successful if the value of that argument is 1, 2, 4, or 5. This is meant to demonstrate how you might implement some type of voting system, where 1 through 5 represents the range of choices and 3, for some reason, is not currently a valid choice.

The web service method then sets two variables: a boolean valid that indicates if the call was successful, and a string value that contains a message with the result of the call. The method then returns an anonymous type that contains both of these values.

Note: As mentioned, my demonstration method is very simple. Were this an actual application, the code would probably update the database or perform other tasks. If your web service needs to access any session state values, you'll need to modify the [WebMethod] attribute for the ProcessItem() method to instead be [WebMethod(EnableSession = true)].

Listing 1: The ProcessItem Web Service

public class UpdateServer : System.Web.Services.WebService
    public object ProcessItem(int itemId)
        bool success;
        string message = null;

        // Indicate success for items 1, 2, 4, and 5
        switch (itemId)
            case 1:
            case 2:
            case 4:
            case 5:
                success = true;
                message = "Server successfully updated!";
            case 3:
                success = false;
                message = "Sorry, that item is not currently allowed.";
                success = false;
                message = "Whoa! That should never happen. Been tweaking around with the markup?";
        return new { Success = success, Message = message };

Calling the Web Service

Now that we have our web service method, we want to call it from our web page. Listing 2 shows a very simple ASPX page that displays 5 boxes. When the user clicks one of the boxes, some jQuery code passes the value of the box that was clicked to the ProcessItem() web service.

Listing 2: Page that uses AJAX to Call the Web Method

<%@ Page Title="AjaxDemo" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="AjaxDemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title>AJAX Demo</title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <style type="text/css">
        body {
            font-family: Arial, Sans-Serif;
            font-size: small;
        .click-item {
            color: White;
            background-color: Green;
            font-size: large;
            font-weight: bold;
            padding: 2px 8px 2px 8px;
            margin: 2px 4px 2px 4px;
            cursor: pointer;
        .unavailable {
            background-color: Maroon;
    <form id="Form1" runat="server">
    <h1>Call Web Service from AJAX Demo</h1>
        Click on one of the following boxes to submit an AJAX request.
        Only green boxes will be successful.
        <span class="click-item">1</span>
        <span class="click-item">2</span>
        <span class="click-item unavailable">3</span>
        <span class="click-item">4</span>
        <span class="click-item">5</span>

<script type="text/javascript">

    $(document).ready(function () {
        $('.click-item').click(function () {
                url: 'UpdateServer.asmx/ProcessItem',
                type: 'post',
                contentType: 'application/json',
                data: '{"itemId":' + $(this).text() + '}',
                success: function (result) {


The code in Listing 2 calls the jQuery function $.ajax() to perform an AJAX post. Note that jQuery also provides a $.post() function that performs basically the same task. However, in my testing I had some trouble with $.post() and found some recommendations against its use. Since $.post() is simply a wrapper for $.ajax(), it may make more sense to learn $.ajax() anyway since it provides more flexibility.

The success item is my function that gets called after the web service successfully returns. The argument to this function contains the data my web service returned. Note that, using this convention, I must use the d member to access my actual data. In this case, the message I returned is available as result.d.Message.

Another item that you can supply to $.ajax() is the error function. This is the function that gets called if the AJAX call fails. Note that this has nothing to do with our web service returning an error value. The error function gets called if there was an error calling the web service or there was an error processing the results.


That's about all there is to it. If you download the demo, you'll see that you can click on any of the boxes and see a message box display the results, all without leaving the current page. For a lot of tasks, performing them without a page refresh can improve the user experience and make your website more enjoyable for users.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.