Using jQuery to make ajax calls to an ASMX web service using ASP.NET

Download source

Making ajax calls to an ASP.NET web service using jQuery is too easy.  In this post I’ll explain how to do it!

Start by creating a new web project and adding a new ASMX web service:

asmx

Open the new web service and uncomment the following line to allow the web service to be called from script.

[System.Web.Script.Services.ScriptService]

The web service should already have a method called HelloWorld; first I will use jQuery to call this method. 

Create a new page and add a reference to the jQuery library.  Add a button and a label to the form; when the button is clicked I will call the web service and display the result in the label.  My form looks like this:

<form id="form1" runat="server">
    <div>
        <asp:Button ID="btnGo" Text="Go" OnClientClick="CallService(); return false;" runat="server" />

        <asp:Label ID="lblResult" Text="&nbsp;" Width="100%" runat="server" />
    </div>
</form>

You can see I’ve set the OnClientClick property of the button to call a JavaScript function called CallService which I will implement in a moment. I have set the text of my label to a non breaking space and set the width to 100%. This is because I will add a CSS class to the label while calling my web service to show an ajax loader.  Here is the CSS class:

.loading
{
 background-image: url('ajax-loader.gif');
 background-repeat: no-repeat;
}

Finally I need to add the jQuery:

 

<script type="text/javascript">
    function CallService() {
        $("#lblResult").addClass("loading");
        $.ajax({
            type: "POST",
            url: "MyService.asmx/HelloWorld",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Success,
            error: Error
        });
    }

    function Success(data, status) {
        $("#lblResult").removeClass("loading");
        $("#lblResult").html(data.d);
    }

    function Error(request, status, error) {
        $("#lblResult").removeClass("loading");
        $("#lblResult").html(request.statusText);
    }
</script>

The CallService function uses the jQuery ajax function to make the call.  Most of the options are self explanatory. The url needs to be the name of the web service followed by a forward slash and name of the method to call. The contentType is the type to use when sending data to the server, here I’m using JSON. The dataType tells jQuery what type of data to expect back from the call, here I am also using JSON which evaluates the response as JSON and sends a JavaScript object to the successful callback function.  success and error are the functions called upon success or error.  I’m not using data here but will use it in the next example to pass parameters to the web service. For a full list of ajax options have a look here.

You can see that the success function is passed two arguments; the first is the data returned from the call, and the second is some text that represents the status of the call. Here the data can be accessed using ‘data.d’.

The error function can have three parameters; the first is the XMLHttpRequest, the second a string describing the error and the third an optional exception object.  In this function I am setting the text of the label to the status text of the request on error.

Before making the ajax call I add the loading CSS class to the label, which is then removed in each of the callbacks. This shows the animation during the call which is then removed once a response has been recieved. To see this working add the following line to the top of the HelloWorld method in the web service to force a delay:

System.Threading.Thread.Sleep(1000);

Now I can run the application and on clicking the button the web service is called and the text ‘Hello World’ will appear in the label… magic…

ajax_helloworld

So the next step would be sending parameters to the web service.  Add a new method to the service that looks like this:

[WebMethod]
public int Add(int value1, int value2)
{
    return value1 + value2;
}

Now create a new webform like so:

 

<table>
    <tbody>
        <tr>
            <th>
                Value 1:
            </th>
            <td>
                <asp:TextBox ID="txtValue1" runat="server" />
            </td>
        </tr>
        <tr>
            <th>
                Value 2:
            </th>
            <td>
                <asp:TextBox ID="txtValue2" runat="server" />
            </td>
        </tr>
    </tbody>
</table>

<asp:Button ID="btnGo" Text="Go" OnClientClick="CallService(); return false;" runat="server" />

<asp:Label ID="lblResult" Text="&nbsp;" Width="100%" runat="server" />

Upon clicking the button we will pass the values entered in the text boxes to the web service and display the result of the values added together in the label. Here is the jQuery to do this:


<script type="text/javascript">
    function CallService() {
        $.ajax({
            type: "POST",
            url: "MyService.asmx/Add",
            data: "{ 'value1': " + $("#txtValue1").val() + ", 'value2': " + $("#txtValue2").val() + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            error: OnError
        });
    }

    function OnSuccess(data, status) {
        $("#lblResult").html(data.d);
    }

    function OnError(request, status, error) {
        $("#lblResult").html(request.statusText);
    }
</script>

The parameters are passed to the web service using the data option. Here I am passing the parameters as a JSON string appending the values from the text boxes on the form.  Running this form now allows two values to be entered and the result to be displayed in the label:

ajax_params

Hopefully this shows the basics of making ajax controls with jQuery using ASP.NET. I’m still new to jQuery myself and just making posts as I learn things, so I’m sure I’ll add to this post in the future.

Download source

Posted on by Joe in Ajax, ASP.NET, C#, JavaScript, jQuery

16 Responses to Using jQuery to make ajax calls to an ASMX web service using ASP.NET

  1. Ken

    Thanks, I have been looking for an example like this.

  2. Joe

    Glad it helped Ken

    Joe

  3. Vikas

    Thanks, you code helped me lot.

  4. anhduc.bkhn

    Cảm ơn !
    thanks you ! 😀

  5. Malu

    this helps me to get basic idea to call web service. I tested this works fine. I really appriceate if you can you give some code sample – how to display data when web service method returns dataset to jquery?

  6. Pepe Marino

    My problem is calling the web service from a different domain. What do you suggest for a situation like that one?

    Cheers!

  7. Balwinder Pal

    Hi Joe,

    I am very thankful to you for publishing this example. It is so helpful for me..

    Once again Thankssss…..

  8. Manan

    Hi,

    This helps but not that much..
    I am calling webservice from different domain
    and when I am using the whole url so code is not executed and it doesnt give any error or anything…

  9. Joe

    Hi Manan

    This is due to the Same Origin Policy.

    You can perform a cross-domain Ajax request using JSONP as can be seen here albeit using PHP. Perhaps when I get some time I’ll do a post using an ASMX or WCF service.

    Cheers
    Joe

  10. Suresh

    Thank you very much to you for publishing this example. but if i run this one ,i get only OnError Function.This one comes Internal Server Error.

    could You Tell me What is My Mistake?

  11. Joe

    Hi Suresh

    Without seeing your code I can’t tell you what your issue is. It sounds like the AJAX call is working fine, but there is a server error in the method you are calling. If you look at the response in Firebug that may help you.

    Cheers
    Joe

  12. Joseph

    Just wondering if you got around to doing a cross domain Jquery / ASMX article.

    I can’t get it to work using JSONP and it is driving me nuts.

    Cheers!

  13. Joe

    Hey

    I haven’t had a chance yet. I’ll try and get to it soon!

    Cheers
    Joe

  14. Darur Ashok

    Thank you very much.. it helped me and web service concept is very much interesting with jQuery.

  15. Victor

    Your code is good, but I downloaded the project and I change the path for this:

    http://localhost/MyWebService.asmx/MyMethod

    And I don’t have a value returned

    Why?

  16. Sibeesh

    Hi,
    Here you are using the webservice in the same application.But my requirement is,
    i have created a webservice in another application and i just need to consume that webservice using jquery.Can you help me with this?And i tried with pasting the url in ajax url section but it is not working.My code is here

    $(document).ready(function () {
    jQuery.ajax({
    type: “POST”,
    url: “http://localhost/DashboardUI/Reports/Marketing/AUSUWs.asmx/getInventoryForWs”,
    contentType: “application/json; charset=utf-8”,
    dataType: “xml”,
    success: function (ret) {
    $(ret).find(“Table”).each(function () {
    alert(‘success’);

    });
    },
    error: function (httpRequest, textStatus, errorThrown) {
    alert(“status=” + textStatus + “,error=” + errorThrown);
    }
    });
    });

Add a Comment