XMLHttpRequest to make Ajax Call using Javascript in Asp.Net C# VB.Net Application

In this AJAX Tutorial i will try to explain “What is AJAX” & how you can start to learn AJAX from very basic. Ajax means Asynchronous JavaScript and XML. Asynchronous means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. Ajax is not a new technology but in these days we found it in a new way. Currently almost all developers want to implement Ajax functionality to achieve asynchronus call back. ASP.NET gives us huge facility to implement Ajax functionality by using ScriptManager and UpdatePanel within very short time. But in this Ajax tutorial i will discuss about Ajax very basic pillar XMLHttpRequest, which is the generic HTTP client for JavaScript.

Steps to call a serverside page by javascript using AJAX:
1. Declare an XMLHttpRequest object.
2. Instantiate the object.
3. Write a function to receive server side data
4. Make a call to server asynchronously
5. Send

Our Example:
In our example we will call an aspx page from another aspx page. Let’s say we will call a page named “ReceiveAjaxCall.aspx” from “Default.aspx” page. To do that we will place one server side Button control and one HTML Button control in Default.aspx page. When we click any Button control then XMLHttpRequest javascript object initiated and collect ReceiveAjaxCall.aspx response asynchronously. First add the asynchronous call script as well as modify the Default.aspx HTML markup in below way:

    <script language="javascript" type="text/javascript">
        function CallAjaxFunction() {
            var AjaxObject;

            try {
                // For Other Browsers Like Opera, Mozilla Firefox, Safari
                AjaxObject = new XMLHttpRequest();
            }
            catch (e) {
                // For Internet Explorer
                try {
                    AjaxObject = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    try {
                        AjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                        // Something might wrong here
                        alert("Your browser does not spport XMLHTTP request!");
                        return false;
                    }
                }
            }

            // Create a function that will receive data sent from the server
            AjaxObject.onreadystatechange = function () 
            {
                if (AjaxObject.readyState == 4) // Response came / server side processing completed
                    document.getElementById('<%= lblTime.ClientID %>').innerHTML = 'Current Server Date Time is: ' + AjaxObject.responseText;
            }
            AjaxObject.open("GET", "ReceiveAjaxCall.aspx", true);
            AjaxObject.send(null);
        }
    </script>


    <div>
        <label runat="server" id="lblTime" style="font-family:Tahoma;font-weight:bold;color:Blue;font-size:1.2em"></label>

        <br />
        <br />

        <asp:Button runat="server" id="cmd" OnClientClick="CallAjaxFunction(); return false;" Text="Call XMLHttpRequest Using Asp.Net Button" />

        <br />
        <br />

        <input type="button" onclick="CallAjaxFunction();" value="Call XMLHttpRequest Using HTML Button" />
    </div>

Code Explanation:
Look the difference between IE & non IE browsers ajax object instantiate block. Otherwise your page will not support cross-browser. If you look at the onreadystatechange property then you found that here i have declared a fixed value 4 to determine that the server call is completed. Yes 4 denotes that “The request is complete”. Onreadystatechange has another 4 values like 0,1,2,3 denotes “The request is not initialized”, “The request has been set up”, “The request has been sent”, “The request is in process” respectively. So when we receive 4 then we write the ReceiveAjaxCall.aspx response into our Default.aspx page lblTime label.

The open method is used to set the request type (GET, POST, PUT, or PROPFIND), the URL of the page being requested, and whether the call will be asynchronous or not. The basic syntax for open method is given below:

open(type,url,isAsync,username,password)

Where username, password is optional.

And the send method makes the connection to the URL specified in open method.

Now time for implementation. No need to change ReceiveAjaxCall.aspx HTML markup. Just populate the Page_Load method to prepare a response with current Date & Time like below:

C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(DateTime.Now);
            Response.End();
        }
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.Write(DateTime.Now)
            Response.End()
        End If
    End Sub

Now runt the project. Hope you will get below output:

Practice Example:

<script language="javascript" type="text/javascript">
    function CallAjaxFunction() {
        var AjaxObject;

        try {
            // For Other Browsers Like Opera, Mozilla Firefox, Safari
            AjaxObject = new XMLHttpRequest();
        }
        catch (e) {
            // For Internet Explorer
            try {
                AjaxObject = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    AjaxObject = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    // Something might wrong here
                    alert("Your browser does not spport XMLHTTP request!");
                    return false;
                }
            }
        }

        // Create a function that will receive data sent from the server
        AjaxObject.onreadystatechange = function () {
            if (AjaxObject.readyState == 4) // Response came / server side processing completed
            {
                var abc = AjaxObject.responseText.split('</title>');
                abc=abc[0].split('<title>');
                alert(abc[1]);
            }
        }
        //AjaxObject.open("GET", "ReceiveAjaxCall.aspx", true);
        AjaxObject.open("GET", "http://www.asp.net", true);
        AjaxObject.send(null);
    }
</script>

The above code is for your practice. Keep practicing.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Ajax, Asp.net, C#, VB.Net

Leave a Reply

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

     

*