Geeks With Blogs
Mahesh Anandan blog

Just moved my blog out of the blogger spot and couple of other places.. so let me start with something simple.

Introduction

AJAX stands for Asynchronous Javascript and XML, Although the Term AJAX was introduced in 2005, The power to call server side code without having to post the entire page has been around since 1999. We now have handfull of framework and ideas floating around, check out the ajaxpatterns.org for more information.  Microsoft recently started focusing on AJAX with its ATLAS (still evolving ) framework. Focus of this article is to demonstrate a simple Http Request and Response from Javascript to Web application (AJAX). I will be using ASP.NET to demonstrate the samples, However, you may replace that with anything you want.

Well, I figured this article can be like a hello world for the blog world.

Learn by Implementation

I prefer to research and learn by implementation, So, Lets create a simple Web application project in .NET (2003 or 2005 ) i am using VS.NET 2003 for this demo and Create a Simple WebForm - Page1.aspx. Add another File to your project - Javascript file that will contain all calls to the server. Page1.aspx Page will have a method known as "CallMeFromJavascript(string name)" (the method name says it all )

HTML for Page1.aspx

1. Add a Text Box

2. Add a Button Control with 'onclick' event calling the Javascript Method callServerMethod(this).

3. Runat attribute is optional.

Code behind Content of Page1.aspx

private void Page_Load(object sender, System.EventArgs e)
{
         string nameFromQueryString = Request.QueryString[0] ;
         if(nameFromQueryString == null || nameFromQueryString.Trim().Length == 0)
         {
            // render the form as usual and return ;
             return ;
         }
         else
         {
            this.CallMeFromJavascript(nameFromQueryString);
         }
         return ;
}

private void CallMeFromJavascript(string name)
{
     Response.Output.WriteLine("[" + this.GetType() + "] Received Value : " + name + Environment.NewLine ) ;
     Response.Output.WriteLine("[#END#]");

     // optionally you could set the content length of Response object and content type to truncate response header information.
}

The Javascript File.

Add the following methods in your javascript file

var xhttpRequest;

function GetXMLHttpRequestFactory()
{
  try
  {
      return ( new ActiveXObject("Msxml2.XMLHTTP2") ) ; 
  } catch (e) {}
  try
  {
    return ( new ActiveXObject("Microsoft.XMLHTTP") ; 
  }
   catch (e) {}

  try
  {
    return (new XMLHttpRequest();
  } catch (e) {}
  alert(" Your browser does not have XML Http Capability. Get IE, Firefox , Opera.");
  return (null);
}

function callServerMethod(control)
{
    xhttpRequest = GetXMLHttpRequestFactory(); 
    if (xhttpRequest == null ) return ;
    xhttpRequest.open("GET" , "Page1.aspx?name=" + control.value + "" , true );
    xhttpRequest.onreadystatechange = processResponse ;
    xhttpRequest.send(null);
    return ;
}

function processResponse()
{
      if (xhttpRequest == null ) return ;
      if (xhttpRequest.readyState != 4 ) return ; // not gonna worry about error handling at this time .
      var responseText = xhttpRequest.responseText ; 
      responseText = responseText.substring(0, responseText.indexOf("[#END#]") - 1 ) ; 
      if (responseText.length > = 1)
      {
          alert(" response From Server : " + responseText );
      }
      xhttpRequest = null ;
      return ;
}

Code Analysis

The Code behind is quite simple, Page Load method checks for a query string in the url and call our method only if you have a query string. (you could make this more intelligent- Lets keep it simple and stupid.).

The client side event handler, On click event calls the javascript javascript method "callServerMethod".

The Method GetXMLHttpRequestFactory() is a Factory method instantiating the client side (Browsers) HTTP Capable object. In Microsoft IE, its usually a ActiveX object, Other browser may Implement bare-minimum XMLHttpRequest Specification from w3c.

The Server method GetXMLHttpRequestFactory() should cover most browsers on the net (both Windows and unix variances ).

Its very simple, Call the Page1.aspx (it could be anything - For example: a web service or different aspx page ) using GET Method and register an event handler to handle the request received.

As you know the Response Stream can be huge and we don't want any of the HTTP Header information, The CallMeFromJavascript Method writes out the response before the response header with a response terminating string [#END#]. (The Terminiating string is not part of W3 Standard for HTML Response). Another strategy is to set the response content type and content length to automatically size the Http Response header and body information.

That's it we are done. Just another Hello World application in AJAX Style.

AJAX.net framework allows you to call a Class or any qualifying object or static type. This can be achived by intercepting the HTTP Pipeline using a HttpHandler and Modifying the Stream with return value from the AJAX Targeted Server side resource(web service, class or anything). ATLAS Framework goes beyond what AJAX can do and performs invalidate Control rectangle and more... But behind the scene its that one single javascript to initiate the call and a Http Handler Request interceptor.

Debugging

Debugging a AJAX Framework can be very challenging especially when the request is mangled with several intercepting handlers and modules.
However, the sample scripts in this article can be debugged quite easily without any problem in VS.NET. Just enable script debugging in your Browser to debug your javascript and to debug your server side you can either run in Debug mode or attach the process. When working with AJAX.NET and ATLAS, i prefer to use HTTP Proxy debugger tool such as Fiddler.

GET & Post issue. When working with XMLHttpRequest, remember GET Request caches your response and you may not see your values or content reflecting the changes on the server side. Using POST solves that problem.  

Replace the    

xhttpRequest.open("GET" , "Page1.aspx?name=" + control.value + "" , true );

To

    xhttpRequest.open("POST" , "Page1.aspx?name=" + control.value + "" , true );

Conclusion

For complex Server side requirement you may want to use a Good framework such as AJAX.net or ATLAS, However, if you are developing application in JSP or ASP technologies, where there is no support for Re-Entrant pages and viewstate, you may find the strategy presented here quite usefull to develop upon. I prefer to use this strategy for simple .net throw away applications.

During my research, I learnt two things:

1. I completely forgot that Linux Browsers does not have ActiveX objects, after extensive googlinnnng, i found that Creating an instance of XMLHttpRequest is more than enough to reach many browsers (including IE). It is possible that GetXMLHttpRequestFactory may return null, if you do, Please send me a brief email about your browser type and installed components (including other custom extensions).

2. XHttpRequest and the ActiveX object returned from the Browser is quite good. You cannot hijack the request to another site. xhttpRequest.open("GET" , "Page1.aspx?name=" + control.value + "" , true ); can ONLY call resources (page , service ) on the same domain (Not even a sub-domain). However, this can be achieved by manipulating the server side code or Intercepting HttpHandlers .

  • This article does not focus on Response Error handling & Response Time out.
  • The javascript provided in this article works just fine for any size requests and response (just be sure to change the alert to something else).

Good sites to book mark:

 

Posted on Wednesday, August 16, 2006 5:45 PM | Back to top


Comments on this post: Hello world on Blog - AJAX Simplified.

# re: Hello world on Blog - AJAX Simplified.
Requesting Gravatar...
How to manipulating server side code to enable request from another server?
Please an example.
Left by sarkoezi on Aug 30, 2007 10:07 AM

# re: Hello world on Blog - AJAX Simplified.
Requesting Gravatar...
Humm... interesting,

I'm learnig javascript and ajax for a while and I wanted to implement a drag and drop feature apparently no matter what I do it does not work do you have any sample code for that?

Thanks for writing about it
Left by web development company on Aug 21, 2009 10:28 AM

Your comment:
 (will show your gravatar)


Copyright © Mahesh Anandan | Powered by: GeeksWithBlogs.net