In this article I will explain with an example, how to use
jQuery AJAX in
ASP.Net WebForms.
Syntax
The following figure describes a
jQuery AJAX call.
HTML Markup
The
HTML Markup consists of:
TextBox - For capturing Name.
The
HTML Button has been assigned an
onclick event handler which calls
ShowCurrentTime JavaScript method to get the
Current Time.
YourName :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Client Side Methods
Inside the
document.ready event handler, the
ShowCurrentTime method makes an
AJAX call to the server and executes the
GetCurrentTime Web Method which accepts the
username and returns a string value.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.js"></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 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
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads