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

 

Comments (1) -

vigrx plus
vigrx plus
4/25/2012 7:12:09 PM #

vigrx plus

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

VSAchievements

Visual Studio Achievements
abhilashca (132 Points)
  • Don't Try This At Home
    • Magic Numbers
      Magic Numbers (0 Points)
      Write a enum with 30 fields. Who needs numbers when you've got words! Uses FxCop
      2 days ago
    • Overload
      Overload (0 Points)
      More than 10 overloads of a method. You could go with this or you could go with that. Uses FxCop
      Wednesday, February 13, 2013
    • Go To Hell
      Go To Hell (0 Points)
      Use of the goto keyword. Um, I heard it was a best practice that you weren't supposed to do that anymore.
      Friday, January 04, 2013
    • Scroll Bar Wizard
      Write a single line of 300 characters long. Who needs carriage returns? Uses FxCop
      Thursday, December 27, 2012
  • Power Coder
    • Time For An Upgrade
      A solution takes 10 minutes to compile. Dag, that's one enormous solution!
      Friday, May 03, 2013
    • Suspicious
      Suspicious (10 Points)
      Use 5 preprocessor directives. Compiler commands -- aren't you fancy!
      Friday, February 22, 2013
    • Equal Opportunist
      Equal Opportunist (10 Points)
      Write a class with public, private, protected and internal members. It's all about scope. Uses FxCop
      Monday, January 21, 2013
    • On The Shoulders of Giants
      Reference 25 assemblies. Hey, why should you write it if someone else already did?
      Tuesday, January 08, 2013
    • Localization Guru
      Localization Guru (10 Points)
      Have 1000 localized values. Nice localization work!
      Thursday, January 26, 2012
  • Just For Fun
    • Save A Tree
      Save A Tree (5 Points)
      Print source code. My boss told me to. I swear!
      Monday, March 04, 2013
    • Obsessive Compulsive Disorder (OCD)
      Invoke the 'Close All But This' menu option 10 times. I mean, who invented those damn tabs anyway?
      Sunday, February 26, 2012
    • Lonely
      Lonely (5 Points)
      Code on a Friday or Saturday night. Coding? Tonight? Ouch.
      Saturday, February 04, 2012
    • Install and Register For Visual Studio Achievements
      Install the add-in and register with Channel9. You are up and running!
      Sunday, January 22, 2012
  • Windows 8
  • Unleashing Visual Studio
    • The Explorer
      The Explorer (5 Points)
      Start a debug session using step into (F11) more than 10 times. Ah, the power of F11. Every coder's best friend.
      Monday, February 27, 2012
    • Casual Observer
      Casual Observer (5 Points)
      Start a debug session using step over (F10) more than 10 times. I thank the debugger every day.
      Saturday, February 11, 2012
  • Good Housekeeping
    • Regional Manager
      Regional Manager (7 Points)
      Add 10 regions to a class. Your code is so readable, if I only didn't have to keep collapsing and expanding!
      Thursday, February 02, 2012
  • Customizing Visual Studio
    • Extensions Junkie Deluxe
      Install 10 extensions to Visual Studio. How can you find anything on a menu?
      Sunday, January 22, 2012
    • Extensions Junkie
      Install 5 extensions to Visual Studio. Extensibility rocks!
      Sunday, January 22, 2012

Month List

Tag cloud