Calling ASP.Net WebMethod using jQuery AJAX

HTML Markup
The following HTML Markup consists of an ASP.Net TextBox and an HTML Button.
Your Name :
    onclick=”ShowCurrentTime()”/>
Client Side Script
When the Button is clicked the ShowCurrentTime JavaScript function is executed which makes an AJAX call to the GetCurrentTime WebMethod. The value of the TextBox is passed as parameter to the WebMethod.
function ShowCurrentTime() {
    $.ajax({
        type: “POST”,
        url: “CS.aspx/GetCurrentTime”,
        data: ‘{name: “‘ + $(“#”)[0].value + ‘” }’,
        contentType: “application/json; charset=utf-8”,
        dataType: “json”,
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
The WebMethod
The following WebMethod returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) and Shared (VB.Net) and is decorated with WebMethod attribute, this is necessary otherwise the method will not be called from client side jQuery AJAX call.
C#
[System.Web.Services.WebMethod]
publicstaticstring GetCurrentTime(string name)
{
    return”Hello ” + name + Environment.NewLine + “The Current Time is: “
        + DateTime.Now.ToString();
}
VB.Net
<System.Web.Services.WebMethod()> _
PublicSharedFunction GetCurrentTime(ByVal name AsString) AsString
   Return”Hello ” & name & Environment.NewLine & “The Current Time is: ” & _
            DateTime.Now.ToString()
EndFunction
Advertisements