In this article I will explain with an example, how to make
AJAX calls using
JavaScript and
XmlHttpin ASP.Net using C# and VB.Net.
This article will illustrate how to get the Current Server Time by making
AJAX call using
JavaScript XmlHttp function in ASP.Net with C# and VB.Net.
HTML Markup
The HTML Markup consists of:
TextBox – For capturing UserName.
Button – For showing current time.
The Button has been assigned with an OnClick event handler.
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Server Side implementation
The GetCurrentTime WebMethod returns a greeting message to the user with his Name and 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
Client Side implementation
When the Button is clicked, the ShowCurrentTime JavaScript function is called.
Finally, the returned string message i.e. UserName and Current Server Time is displayed using the
JavaScript Alert Message Box.
<script type="text/javascript">
function ShowCurrentTime() {
var name = document.getElementById("<%=txtUserName.ClientID%>").value;
var request;
if (window.XMLHttpRequest) {
//New browsers.
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
//Old IE Browsers.
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request != null) {
var url = "Default.aspx/GetCurrentTime";
request.open("POST", url, false);
var params = "{name: '" + name + "'}";
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(JSON.parse(request.responseText).d);
}
};
request.send(params);
}
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads