In this article I will explain with an example, how to make AJAX call to Server Side Web Service's WebMethod using jQuery in ASP.Net using C# and VB.Net.
jQuery allows to call Server Side ASP.Net methods from client side without any PostBack. It is an AJAX call to the Server but it allows us to call the method or function defined in server side.
 
 
Syntax
Below figure describes the syntax of jQuery AJAX call.
Make AJAX Call to ASP.Net Server Side Web service method using jQuery
 
 
HTML Markup
The HTML Markup consists of a TextBox and a HTML Button. The HTML Button has been assigned an onclick event handler which calls ShowCurrentTime JavaScript method to get the Current Time.
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
 
 
Client Side Methods
The ShowCurrentTime method makes an AJAX call to the server and executes the GetCurrentTime Web Method which accepts the UserName as parameter and returns a Server’s Time as string value.
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script>
 
 
Server Side Web Methods
The GetCurrentTime method simply returns a greeting message to the user along with the current server time.
Note: The method is declared as static (C#) and Shared (VB.Net) and also it is declared as WebMethod unless you do this you won’t be able to call the methods.
 
C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}
 
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
        DateTime.Now.ToString()
End Function
 
 
Screenshot
Make AJAX Call to ASP.Net Server Side Web service method using jQuery
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads