Click here to Skip to main content
Click here to Skip to main content

AJAX Demystified - Part One - The AJAX Shoutbox

, 20 Sep 2006
Rate this:
Please Sign up or sign in to vote.
Create your own AJAX Shoutbox using ASP.NET and C#.

Sample Image - shoutbox.gif

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

UsualDosage
Architect
United States United States
I have been an ASP.NET/C# Programmer/Software Architect for about 10 years, specializing in web architecture, user interface, and user experience. I formerly wrote business applications for mortgage banking front-ends in C++ before switching to the .NET Framework many years ago, and I've never looked back. I'm an evangelist of HTML5 and web standards, and spend the majority of my time working on front end design, performance and scale.

My primary website is located at http://www.usualdosage.com

Comments and Discussions

 
Questionhelp anyone Pinmembersimran229-May-12 11:36 
GeneralUpdate the message PinmemberKillshadow18-Mar-09 20:29 
Questionoverload resolution failed becouse no accessible 'write' Pinmemberthalz1428-Aug-07 22:43 
AnswerRe: overload resolution failed becouse no accessible 'write' PinmemberUsualDosage9-Aug-07 0:28 
GeneralRe: overload resolution failed becouse no accessible 'write' Pinmemberthalz1429-Aug-07 6:26 
Generalneed help Pinmemberchronorick18-Apr-07 16:56 
GeneralRe: need help PinmemberUsualDosage19-Apr-07 3:54 
Sounds like an IIS configuration issue. I'll try to help you out here by showing you how my IIS is configured, and hopefully that will solve the problem.
 
Launch the Internet Information Services (Control Panel->Administrative Tools->Internet Information Services).
 
In the left treeview, you will see something like Your Computer Name->Websites->Default Web Site->Name of your Shoutbox Website. Right click on the name of your Shoutbox website, and select "Properties".
 
Select the Directory Security tab. Under Anonymous Access and Authentication Control, click the "Edit" button.
 
Ensure the "Anonymous Access" checkbox is checked, as well as "Integrated Windows Authentication". Once done, click OK, and close out of the properties window.
 
That should allow your site to be browsed (if the site was initially configured properly in IIS) to be browsed anonymously.
 
Hope it helps!
 
-UD
 

 
Quae narravi nullo modo negabo.

GeneralRe: need help Pinmemberchronorick19-Apr-07 18:47 
GeneralRe: need help PinmemberUsualDosage23-Apr-07 3:07 
GeneralRe: need help Pinmemberchronorick25-Apr-07 22:21 
GeneralNice Job.. PinmemberSaadz12-Apr-07 7:44 
GeneralRe: Nice Job.. PinmemberSaadz12-Apr-07 7:54 
Questioncaracters problem Pinmembermasterpage19-Jan-07 0:40 
AnswerRe: caracters problem PinmemberUsualDosage19-Jan-07 4:21 
GeneralThank you for the lesson PinmemberTaeKwonJoe25-Nov-06 23:09 
GeneralMicrosoft and AJAX support PinmemberDenzel2-Oct-06 1:36 
GeneralRe: Microsoft and AJAX support PinmemberUsualDosage2-Oct-06 3:36 
Questioncall me stupid but... Pinmembertopknot6921-Sep-06 5:13 
AnswerRe: call me stupid but... PinmemberUsualDosage21-Sep-06 5:26 
GeneralRe: call me stupid but... Pinmembertopknot6921-Sep-06 6:08 
GeneralRe: call me stupid but... PinmemberUsualDosage21-Sep-06 6:16 
GeneralRe: call me stupid but... Pinmembertopknot6921-Sep-06 6:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 20 Sep 2006
Article Copyright 2006 by UsualDosage
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid