Calling ASMX web service via JQuery ajax

.NET, AJAX, jQuery 6 responses so far

In this article, I want to show how one can call ASMX web service from his or her JQuery client code and also show the subtle issues that he or she might encounter. To be more specific, I want to show how to pass a JavaScript object to an ASMX web service method and get the result as a JavaScript object. I prefer JSON format for transferring data back and forth between client-side and server-side code. Therefore, I use JSON in this article.
We want to call a web service method which its name is “GetPersonnelSalaryData” and has the following signature:

public int GetPesonnelSalary(Person p)

The Person class is defined below

public class Person
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string FamilyName { get; set; }
}

To create the ASMX web service do the following steps:
1. Create a new web project, select “ASP.NET Empty web site” – name it “SampleServicePrj”
2. From add new Item (Website -> Add new Items…), select Web Service template – name it “SampleService.asmx”
In order to be able to get JSON from the methods in the ASMX web service, one should put the following attribute on the top of the class

[System.Web.Script.Services.ScriptService]

Therefore the first step is to uncomment that line above the SampleService class.

The resulted code is:


    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class SampleService : System.Web.Services.WebService
    {

        [WebMethod]
        public int GetPesonnelSalary(Person p)
        {
            int salary = 0;
            if (p.ID < 1000)
            {
                salary = 100000;
            }
            else
            {
                salary = 25000;
            }
            return salary;
        }
    }

In order to call it with JQuery we can write the following code:


       var person = {};
        person.ID = $('#txtID').val();
        person.Name = "Amir";

        var pdata = { "p": person };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/SampleService.asmx/GetPesonnelSalary",
            data: JSON.stringify(pdata),
            dataType: "json",
            async: true,
            success: function (data, textStatus) {

                if (textStatus == "success") {
                    if (data.hasOwnProperty('d')) {
                        msg = data.d;
                    } else {
                        msg = data;
                    }
                    alert(msg);

                }
            },
            error: function (data, status, error) {
                alert("error");
            }
        });

For URL parameter one should specify the location of the page that he or she wants to call. In our case the url is in this format: webServiceLocation/methodName. In addition, in order to send and receive JSON, the dataType should be set to json. In order to convert JavaScript object to JSON string one can use JSON2 library (http://www.JSON.org/json2.js). One important thing that one should note that is the ASP.NET 4.0 send the result of the method as a value of a parameter d which is not the case for previous versions of ASP.NET.

 

The following two tabs change content below.

Amir

Latest posts by Amir (see all)

  • gagandeep

    When i code as given above it started working, but again when i am creating any of the web service and giving the url in html page it is not working . Instead i have created the same above given project again it is also not working .. Give me solution . I am just get fad up . i have tried in many ways but not working .

    I have to change my url and its method name only na from my html page in main .js file .

  • Amir

    Hi,
    I can't fully understand your problem. If it is possible please give me the sample code which is not working.
    Regards,
    Amir

  • james

    can this cross domain using jsonp? im having trouble using an external asmx as an api.

    thanks for the article,
    james

  • Shon MX

    How can I prevent a property from being serialized, ultimately excluding it from the JSON representation of my object??

  • a-passer-by

    Line #13 reads…

    if (p.ID < 1000)

    …I presume this is meant to be…

    if (p.ID < 1000)

  • erere

    ererer

x
Loading...