Call asmx web service from jQuery Ajax

I had earlier posted a tutorial on how to call c# server side methods using JavaScript. It made use of Page Method provided by .NET framework.
In this tutorial, we'll see how to call an asmx service web method using jQuery Ajax. So lets start by creating a web application in Visual Studio. Download and include the latest jQuery in your html or aspx page.
<script src=" jquery-2.1.1.js="" scripts="" type="text/javascript"></script>

 Let's add an asmx service to the web application project called HelloSercice.asmx. Next create a new class called Employee.

public class Employee
    public string EmpFirstName { get; set; }
    public string EmpLastName { get; set; }
Create a new web method called GetEmpoyeeDetails which we'll call later using jQuery Ajax as shown below:
public Employee GetEmployeeDetail()
    Employee objEmp = new Employee();
    objEmp.EmpFirstName = "Tech";
    objEmp.EmpLastName = "Illumination";
    return objEmp;
In the above method, we have simply created an Employee object, filled it up with some dummy data and returned it.
Next comes the best part where we need to call the web service method using jQuery Ajax. Let's create a page called index.aspx and create a button and a label.
<input type="button" id="btnCallService" value="GetEmployeeDetail" />
<label id="lblData"></label>
On button click let''s call the asmx web service method as shown below:
$(function() {
    $('#btnCallService').click(function() {
            type: 'POST',
            url: 'HelloService.asmx/GetEmployeeDetail',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function(response) {
            error: function(error) {
Most of the parameters we have used above are quite self explanatory. Only thing  which i believe can be a bit confusing is the dataType. So, let me explain that since we are passing the Employee object from the web service we are expecting it to be in json. We can also return the Employee object as string from the web service and in that case we don't need to set dataType as json. We can leave to default which is text.

One more important thing. In order for the asmx script to be accessible from the client side, we need to include
above the HelloService class else it will throw an error

Only Web services with a [ScriptService] attribute on the class definition can be called from script

Now simply try running the web application and on clicking the button you should be able to see the below output
    "d": {
        "__type": "CallAsmxViajQuery.Employee",
        "EmpFirstName": "Tech",
        "EmpLastName": "Illumination"
Code from this tutorial can be found on GitHub.
Post a Comment