In this article I will explain with an example, how to call Server Side function with parameters using XmlHttpRequest (XHR) in ASP.Net using C# and VB.Net.
This article will illustrate how to get the Current Server Time by making AJAX call to a Server Side function using JavaScript XmlHttpRequest (XHR) in ASP.Net with C# and VB.Net.
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 Server 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 using JavaScript XMLHttp function to the server and executes the GetCurrentTime Web Method which accepts the UserName as parameter and returns a Server’s DateTime as string value.
Then the Server’s Time along with UserName 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) {
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.
public static string GetCurrentTime(string name)
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
<System.Web.Services.WebMethod()> _
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
End Function
Call Server Side function using XmlHttpRequest (XHR) 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.