Today, almost every major site includes at least bits of AJAX calls, whenever to display a shopping cart, to dynamically load fragments of a page, or to pre-fetch the next images in a slideshow. jQuery, mootools, prototype... there is an increasing number of Javascript frameworks that, among other things, allow asynchronous calls to fetch data.
In .NET, although they are starting to migrate to jQuery (as we can see in ASP.NET MVC), by default when you create a .NET 3.5 website it references the not bad but clumbersome ASP.NET AJAX framework. Although I don't have anything against this practice, sometimes we don't need so much, or we might prefer to do things "our way" and for example communicate with the client site using JSON.
So this post is going to be like a small 3 steps tutorial on how to do 100% handcrafted basic AJAX requests using ASP.NET. Then you can so many things to it to make as good as you want.
Step 1: Build a HttpHandler
The most efficient way to develop AJAX call handlers in the server side is to use HttpHandlers. We keep the request context, but we skip all ASP.NET forms additional layers, providing a fast code in exchange of requiring a full implementation and management of the output by us.
- using System;
- using System.Collections.Generic;
- using System.Web;
- namespace Handlers
- {
- public class AJAXHandler : IHttpHandler
- {
- public bool IsReusable
- {
- get
- {
- return true;
- }
- }
- public void ProcessRequest(HttpContext context)
- {
- context.Response.Write("Received " + context.Request.RawUrl + " @ " + DateTime.Now.ToLongTimeString());
- }
- }
- }
Code is quite easy, so just remember to add a reference to System.Web to be able to implement IHttpHandler interface. IsReusable in this case is interesting as we can probably be having lots of requests to the handler.
Step 2: Plug the handler in a web project
We will create the website in the third step but doesn't matters as we just need to add a reference to the handler we've just created, and then edit the web.config to add it, under the <configuration> <system.web> node:
- <httpHandlers>
- <add verb="*" path="*.ajax" type="Handlers.AJAXHandler, Handlers"/>
- </httpHandlers>
We're configuring our site to enroute all calls that end in .ajax to our handler.
Step 3: Client side coding
Finally, we get to the important part: Making async calls from our webpages. The following example is for one page, of course to reuse it you should place all the <script> code inside a .js file and reference it.
We're using asynchronous responses using a callback function to not block anything, but yet this is a simple and standard code without advanced checks, no request manager engine, no error handling...
- <div>
- <div id="test_placeholder"></div>
- <input type="button" value="Test" onclick="javascript:AJAXCall('test.ajax', 'test_placeholder');" />
- </div>
- <script type="text/javascript">
- var xmlhttpReq;
- var targetElement;
- function AJAXCall(Url, Target)
- {
- targetElement = Target;
- if (window.XMLHttpRequest)
- {
- xmlhttpReq = new XMLHttpRequest();
- }
- else
- { // code for IE5-6
- xmlhttpReq = new ActiveXObject("Microsoft.XMLHTTP");
- }
- xmlhttpReq.onreadystatechange = ajax_response;
- xmlhttpReq.open("GET", Url, true);
- xmlhttpReq.send(null);
- }
- function ajax_response()
- {
- // 4 completed, 3 in progress
- if (xmlhttpReq.readyState == 4 && xmlhttpReq.status == 200)
- {
- if (xmlhttpReq.responseText)
- {
- // responseText contains output
- document.getElementById(targetElement).innerHTML = xmlhttpReq.responseText;
- }
- else
- {
- document.getElementById(targetElement).innerHTML = '';
- }
- }
- }
- </script>
Each time we click on the button we'll see a timestamped response.
From here, you can improve the handler (or add more) to handle JSON, XML, even HTML templates, the limit is your imagination ;)
Tags: Development