post-ad

AJAX Calls Using JavaScript And XMLHTTP in ASP.Net

In this tutorial, I’ll demonstrate how to create AJAX calls in ASP.Net with C# using JavaScript and XMLHttp.
This article will demonstrate how to use ASP.Net with C# to make an AJAX call using the JavaScript XMLHttp method to obtain the Current Server Time.

HTML Markup:

The GetCurrentTime web method, which accepts the UserName as an argument and returns a Server’s DateTime as a string value, is called by the ShowCurrentTime method via an AJAX call using JavaScript’s XMLHttp function.
The JavaScript Alert Message Box then shows the UserName and the Server’s Time.

<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>

Server Side Web Methods:

Simply a greeting and the current server time are returned to the user by the GetCurrentTime function.

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories

page-ad