Calling a Webmethod Using Jquery Ajax

Introduction

This tip explains how to call a web method using JQuery.There are so many ways we can do this requirement. Here I am explaining one.

Steps

  1. We need to include:
    1. <script src="Script/jquery-1.9.1.min.js" type="text/javascript"></script>  
  2. After that, create an Ajax jQuery function like this:
    1. function checkUserNameAvail() {  
    2.     var userid = $("#reguser").val();  
    3.     jQuery.ajax({  
    4.         type: "POST",  
    5.         url: "Login.aspx/checkUserNameAvail"//It calls our web method  
    6.         contentType: "application/json; charset=utf-8",  
    7.         data: "{'iuser':'" + userid + "'}",  
    8.         dataType: "xml",  
    9.         success: function (msg) {  
    10.             $(msg).find("Table").each(function () {  
    11.                 var username = $(this).find('UserName').text();  
    12.                 if (username != '') {  
    13.                     //window.location.replace('/iCalendar.aspx');  
    14.                     alert('This username already taken..');  
    15.                     $("#reguser").val('');  
    16.                     $("#reguser").focus();  
    17.                 }  
    18.                 else {  
    19.                 }  
    20.             });  
    21.         },  
    22.         error: function (d) {  
    23.         }  
    24.     });  
    25. }  
  3. Make sure that you have included the js file to the aspx page.

  4. Create a web method in your aspx.cs file like the following:
    1. [WebMethod(enableSession: true)]  
    2.    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]  
    3.    public static string checkUserNameAvail(string iuser)  
    4.    {  
    5.        try  
    6.        {  
    7.            //This is where i am returning my data from DB  
    8.   
    9.            iCalendarClass iC = new iCalendarClass();   
    10.            DataSet ds = iC.checkUserNameAvail(iuser);  
    11.            return (ds.GetXml());  
    12.        }  
    13.        catch  
    14.        {  
    15.            return null;  
    16.        }  
    17.    }  

Make sure that your function returns XML.

That's all. Have a happy coding :)

Ebook Download
View all
Learn
View all