CameTooFar

A Nerd's False Positive.

A Forgotten Story - Ajax in ASP.NET using JavaScript


This post explain how to perform an Ajax call in an asp.net page, using native Ajax code. There is nothing New with this post, its typically an old school note. But, you can still see developers who don’t know how to make a raw/plain Ajax call in asp.net, but knows how to perform Ajax call using jQuery, ASP.NET AJAX or any other frameworks.

In a nut-shell, frameworks like jQuery and ASP.NET AJAX are wrappers written over the raw/plain Ajax. Of course, they make our work easy and simple, but these frameworks hides the core concept. Hence an average amount don’t understand what happens really under the hoods and will gaze while troubleshooting a web application.

Ajax is not a technology, but a technique for creating fast and dynamic interactive web pages.

In this post, I’ll demonstrate a simple example on how to send data from client-side to server-side, using Ajax and to get a response (Callback) from server-side.

[Design]

Server-side

[Ajax Script]

This is the Ajax script that send the details to the server.

<script type="text/javascript">
    function sendViaAjax() {
 
        // Build URL to make Ajax call
        var url = "Test.aspx?name=" + document.getElementById("txtName").value;
 
        // Creates an Ajax call object
        var xmlHttp; = new XMLHttpRequest();
 
        // Specify URL to connect
        xmlHttp.open("GET", url, true);
 
        // Callback function to handle response from Server
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    alert(xmlHttp.responseText);
                }
            }
        };
 
        // Send Ajax request to Server
        xmlHttp.send();
    }
</script>

where,

XMLHttpRequest XHR is an API in JavaScript, which allows to send both HTTP/HTTPS requests directly to the web server and load the server response data (plain-text/xml) directly back into the script
   
open Specifies:

a. request type (GET/POST)
b. URL to the server page
c. connection type (Async: true, Sync: false)
   
send Send the request to server
   
onreadystatechange Sets the callback function to handle the response from server
   
readyState Holds the status of XHR:

0:   request not initialized
1:   server connection established
2:   request received
3:   processing request
4:   request completed & response is ready
   
status Retrieves the HTTP status-code of the response

200: OK
404: Page not found
   
responseText Retrieves the response body as a string
   

 

[Server Side Code]

The server-side code that accepts the Ajax request and send response back to client-side looks like

protected void Page_Load(object sender, EventArgs e)
{
    string ajxValue = "Hello " + Request.QueryString["name"] + " !";
 
    Response.Write(ajxValue);   // Write the Response
    Response.End(); // End Response
}

In the above snippet, value passed from the client-side is read as QueryString and writes back to the client-side after modification.

Please note, once the response is written, we immediately calls Response.End() method. This is done so that only the ajxValue will be available in the response stream. Else, the entire html of the page will be available along with the ajxValue, in the response stream.

A sample output, without calling Response.End()looks like

ajaxresponse

The complete solution can be summed-up as

[Default.aspx]

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function sendViaAjax() {
 
            // Build URL to make Ajax call
            var url = "Test.aspx?name=" + document.getElementById("txtName").value;
 
            // Creates an Ajax call object
            var xmlHttp = new XMLHttpRequest();
 
            // Specify URL to connect
            xmlHttp.open("GET", url, true);
 
            // Callback function to response from Server
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        alert(xmlHttp.responseText);
                    }
                }
            };
 
            // Send Ajax request to Server
            xmlHttp.send();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Enter Name: "></asp:Label>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="Send To Server" onclick="sendViaAjax();" />
    </div>
    </form>
</body>
</html>

[Test.aspx]

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ajxValue = "Hello " + Request.QueryString["name"] + " !";
 
        Response.Write(ajxValue);   // Write the Response
        Response.End(); // End Response
    }
}

Hope this helped.

Happy Dynamic and Ajax Rich Programming!

Download Sample

For more details, spend some time with following links:

1. http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx
2. http://www.w3schools.com/ajax/ajax_intro.asp
3. http://en.wikipedia.org/wiki/List_of_HTTP_status_codes


Thanks