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.
public static string GetCurrentTime(string name)
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
End Function
Client Side implementation
When the Button is clicked, the ShowCurrentTime JavaScript function is called.
Inside this function, an AJAX call is made to the Web Methodusing JavaScript XmlHttp function to the GetCurrentTime Web Method and the value of TextBox is passed to it.
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";
  "POST", url, false);
            var params = "{name: '" + name + "'}";
            request.setRequestHeader("Content-Type", "application/json");
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
AJAX Calls using JavaScript And XmlHttp in ASP.Net
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.