Introduction
AJAX stands for Asynchronous JavaScript and XML, and is one of the fastest growing technologies on the web, leading the charge for the "Web 2.0" generation. While definitely not a "new" technology per se, it's only recently gained market share with its use by Google, Wikipedia, and numerous other sites. This article won't go into great depth about what AJAX is (you can find more information about it by visiting Wikipedia), but will delve into some simple concepts that will help you easily implement AJAX into your next ASP.NET application.
Background
Microsoft seems to have been slow to adopt AJAX, having very little support for it in .NET 1.1 and VS2003. They did release ATLAS, which was their set of libraries that aided in the implementation of AJAX in .NET 2.0. You can read more about ATLAS on Wikipedia. But, rather than just dump some libraries on you and say "have fun", I'd prefer to illustrate the usage of the XMLHttpRequest
object, and show how easy it can be to implement its functionality into your website with very little overhead.
Getting started
The reason I like AJAX so much is two-fold. First, I like that websites don't have to do continual postbacks to gather information. Secondly, I like how AJAX is a "jack of all trades" technology. It takes a little knowledge of HTML, a little knowledge of JavaScript, a little knowledge of a server-side scripting language (PHP, ASP.NET, etc.), and a little knowledge of CSS. So, before launching into this, it'd be good to have these tools at your disposal. While the code I'm going to present is not that complicated, a fundamental knowledge of the above four technologies is definitely required.
Overview
The root functionality of AJAX lies in the XMLHttpRequest
object. There are four primary steps in utilizing this object.
- Create the request
- Send the request
- Receive the response
- Process the response
In the Shoutbox sample, I use a separate JavaScript function to handle each task. All we're really doing, in layman's terms, is accessing the XMLHttpRequest
object, adding a delegate to handle the response processing, giving it a URL with the address of our server-side script (and including any query string variables we want), then waiting for the server-side script to pass us back a response. The great thing about the response is that it's basically just text we're going to be getting back, so it could be formatted HTML, a comma delimited list, an XML document, etc. So, once we have the response from the server, we use JavaScript to put the text into a table
, div
, span
, etc.
Using the code
There are several different steps to creating and using the code. Because AJAX uses multiple technologies to accomplish its tasks, I'll break it down here with a brief explanation using my included example:
- shoutBox.aspx - Honestly, doesn't even need to be an ASP.NET page. This could be just a standard HTML file. It contains the HTML that we will use to activate the JavaScript and display the response.
- shoutBox.js - This is the JavaScript file (referenced from the shoutBox.aspx page) that handles all of our request processing.
- shoutbox.xml - Houses all of the messages in XML format.
- shoutbox.css - The stylesheet. This is optional, but will definitely help make your app look cool.
- saveXML.aspx - The HTML page is nothing...We're only interested in the code-behind. This is the server-side script that handles the XML request, does all of the processing, and returns a response.
I'm not going to include a lot of source code in this article, because the code I'm providing in the source is fairly well documented. If you're fairly up to date on your C#, the provided server-side code should be a no brainer for you. If not, I'll explain the three methods:
Page_Load()
- Here, we receive the query string from the XMLHttpRequest
object, save the message to our XML file (see below), and write out a response (the response contains our formatted messages in HTML format).
saveNewMessage()
- Accepts a message string and a username. This adds a new node to the XML file with the message, and saves the XML server-side.
getMessages()
- This loads the messages from the XML file, creates a data table, and loads the messages in as rows, sorts the data table by the timestamp, and then converts all of the rows in the datatable to formatted HTML. This method returns a string, which is the output in the response.
Points of interest
I tried several JavaScript-ing options before settling on the library I'm providing here. The biggest point of contention I noticed was the exact coding of the response handling delegate (in my code, called processResponse()
). It seems the key to ensuring your XMLHttpRequest
object never loses scope is to declare the variable globally and initialize it once. I was previously attempting to create the object within a function, then pass the object to the delegate as an argument, which failed miserable (I kept getting a type mismatch error).
You may notice that I handle all of the formatting on the server-side, then return a formatted string to the client. I did this for a few reasons. First and foremost, I'm not a JavaScript guru, so processing XML client-side is problematic for me. I'd rather use VS.NET and handle it all server-side with my trusted Intellisense. Secondly, servers are there for one purpose (to quote a recent IBM commercial): "To Serve"! So, why not make them do what they do best?
Feature suggestions
All you'll really need to worry about with this code is styling the Shoutbox using the provided CSS. All of the code should work "out of the box". Some changes you might want to make? Well, for starters, you could easily turn this into a Web Control. You could also scrub the message input for links, and format the anchor tags appropriately. You could make a user login, and capture their login name in a hidden HTML input so they wouldn't need to enter a name. There are a lot of possibilities. Hopefully, this can get you started down the right path.
Security concerns
Some added points you might want to consider: The Shoutbox should be somewhat spam-proof. Entering a single message and clicking dozens of times will only add the message once. There is a check to ensure the Name and Message boxes are at least 1 character long. The Shoutbox will not scrub out links, JavaScript, or any sort of formatted HTML.
Happy coding!
I’m a very hands-on, full-stack, architect and engineer with management and leadership experience. I have operated primarily in the .NET environment, though I embrace Open Source wholeheartedly. I absolutely love writing code, developing standards and patterns, working with talented engineers, and mentoring individuals; I thrive in non-managerial environments. I’m passionate about the technology, science, mathematics, and engineering behind the craft of computer science. Even when I’m not working my full-time job, I’m still honing my technical skills, whether it’s building rockets on my 3D printer, designing software for personal use, writing white papers, or contributing to my many open-source projects.