Name: Mike Griffiths
Location: France

I am a software developer and consultant with more than a quarter of a century of technology change and challenges to draw experience from. While I maintain and exercise some skills from the dark ages of computing I also enjoy taming the new technologies as they turn up – always looking for ways to deliver truly effective software systems to my customers.

Tuesday, February 28, 2006

An Ajax “Hello World” project to get you going

A lead to a great posting Rasmus' 30 second Ajax tutorial was too good a treat not to share around. Sometimes we all want something very simple to build a thorough understanding of the mechanics of a new technique before we dive into the deeper water beyond. Now, if you are into ASP.NET and not PHP you might like to take a look at my version of this ultra-simple introduction to Ajax with sincere thanks to the original author. Now most simple introductions to Ajax using ASP.NET seem to quickly become complex - introducing libraries and DLLs and helper functions just about as soon as the first paragraph is over. This is because they all seem to miss out the fact that you have to work around the ASP.Net functionality to get thing working in a nice simple manner. I will try and take you through the steps that explain the problem and thus make the solutions seem much more obvious.

So let's get going. Create a new Web project and, to keep things very simple at this initial stage, add a couple of HTML controls - a text field and a button to the initial page. Note, not regular ASP.NET web forms controls - click the HTML tab.

Then add a JavaScript file to the project and paste the following into it:

function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro =
new ActiveXObject("Microsoft.XMLHTTP");
}
else{
ro =
new XMLHttpRequest();
}

return ro;
}


var http = createRequestObject();

function sndReq(action) {
http.open('POST', 'WebForm2.aspx?action='+action);
http.onreadystatechange = handleResponse;
http.send(
null);
}


function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
alert(response);
document.getElementById('MessBox').value = response;
}
}


You will need to add a reference to this JavaScript file to the web page - although you could just add the script to that page directly.

I gave my Test Field the name "MessBox" and then added an OnClick event to the button to call the sndReq() JavaScript function. You can check out the two HTML lines at the code repository for this blog

Now add a second page to the project - The default name will be WebForm2.aspx which matches with the hard coded value you will have noticed in the sndReq() JavaScript function above - if you call your new page something else then you will have to adjust the http.open() line in that function.

Do not put any controls on the new page and for a first run just add the following to the PageLoad() sub in the "code behind".

Dim YouSent As String = Request.QueryString(0)
Response.Write("You sent " & YouSent)

Now let us have a quick look at the JavaScript. There is a good explanation of the function at the location linked at the top of this article so I can keep it simple here. The CreateRequestObject() function simply handles the fact that versions of Internet Explorer before version 7 have the XMLHTTPRequest object named as XMLHTTP - in fact this code will need adjustment if it is likely to run into a beta of IE7. The sndReq() function makes an asynchronous call to the specified URL and the handleResponse() function is registered as part of the sndReq() function as the function that will manage any returned responses.

Fire up the application and click the button. The alert() command added to the JavaScript handleResponse() function will show you exactly what comes back. You will see the expected message "you sent foo" followed by the HTML for the empty page - including (nearly) empty HEAD, FORM and BODY tags.

Just to get our first ASP.NET/Ajax app up and running we can make a couple of changes and then think about the implications of what just happened.

First - let's change the Response.Write line to

Response.Write("Hello World") as that was our original intention although it was nice to see that we could pass data to the server as well as retrieve it using our ultra simple Ajax functions.

Then open up WebPage2 in the HTML view and remove all of the code with the exception of the first line (the one that registers the Code Behind). This will stop the ASP.NET page adding it's HTML to the response - because there will be none to add. This can be done programmatically at run time but not from the page load event (as the HTML has not yet been rendered at that point in time).

Then run the application and click the button. We now have a working application that implements Ajax technology with requested data being displayed without reloading the page.

Clearly a more complex web page with multiple opportunities to implement Ajax technology would require a more sophisticated set-up at the client end. Also, while the technique shown could be easily amended to handle multiple requirements at the server end it is probable that you would want individual controls to communicate directly with prepared functions within the same page. In all probability you will want to move on to one of the Ajax control libraries or to implement something like the Ajax.dll file described in the MSDN article ASP.NET Spiced: Ajax that allows you to tag specified functions as "Ajax Methods" and call them from the client. I will take the opportunity to explore one or two of these options in this blog although I am traveling again for the next few days - to the USA this time.

25 Comments:

Anonymous Anonymous said...

What a sucky tutorial... links to example code dont work and you have no explanations for calling methods etc.

2:53 AM  
Blogger Mike Griffiths said...

What a "sucky" comment - although thanks for spotting the typo in one of the links on the page.

The idea of the piece is that you can build a simple .NET Ajax application in (just about) the time it takes to read the simple instructions.

There is so little code that anyone should be able to work out just what is going on.

3:40 AM  
Blogger Mike Griffiths said...

About every couple of weeks some juvenile called "Anonymous" comes by and leaves a message suggesting that this post "sucks".

I have read it through and I can't see why - unless of course the juveniles just want something to copy and paste into a school assignment.

So here is a message to the lazy - you can't acquire new skills without just a little effort. Reading and understanding (preferably actualy running the code of) this very simple intoduction to Ajax will teach you the basics of how it all works. You can then build on this knowledge - and maybe - just maybe acquire some developer skills.

1:45 AM  
Blogger Real Estate said...

Well Said Mike.

7:51 PM  
Anonymous Anonymous said...

hi nice tutorial but i need more codes which help me to learn ajax.,
thnx

2:26 AM  
Blogger Mike Griffiths said...

The key point anonymous is that there is nothing more to Ajax than this 30 second demo (well all right maybe the X part). If you write and run the code you will have a fully working Ajax app.

What follows is all about implementing Ajax in a specific environment. You will get to grips with JavaScript and PHP (in a LAMP environment) or JScript and C# in a .NET environment. There are plenty of resources around to cover that ground - perhaps I will post some links although the number and complexity of the various frameworks seems to increase by the hour.

2:40 AM  
Anonymous Marlon said...

A decent enough tut. I understand what's going on.
Pity about the lazy ungrateful comments though, anyone who makes time to just write a tut, however small or large, should be thanked. And the fact that he couldn't even realise it was a typo in the url, makes him so much more unfit to even try.

12:06 AM  
Anonymous Anonymous said...

Hello, i've been coding for a few months and i've really gotten the hang of cfml. I see Ajax as the oppotunity to really beef up my app. I want to write a simple user authentication module but i really do not understand how to send the data over to my cfm files on the server. And a lil' Comment on the actual java script would help.

8:01 AM  
Blogger Mike Griffiths said...

A fair point I suppose. I have commented before that the post was supposed to be a 30 second introduction and not a tutorial on fully practical implementations. I will have a think and see if I should write something more concrete (after all I use this technology in lots of places) or if I should collect together some suitable links - no point in re-inventing too many wheels.

8:14 AM  
Anonymous Anonymous said...

this is a clean, nice and tidy f example of pure ajax... you may also post a ajax/php script with little modif in the sndReq function

it's a great example !!!! thnx

1:40 AM  
Anonymous Brian Kusumawan said...

The post is great enough to introduce newbies about how Ajax actually works on .Net framework. It's freakin'-clearly-titled as "An Ajax “Hello World” project to get you going" and referring to that title, those who are interested in IT industry should be able to understand that this post is meant to be as simple as possible; dedicated to those who are new with term "Ajax". "Hello World" is apparently a word that is widely used to express simplicity in naming any output when you learn programming for the first time.

Therefore, I hope that the "sucky" Anonymous can take this lesson not to speak if she/he doesn't have any business about something and if you expect to get such a complicated and advanced tutorial, this ain't the place, mate. Buy those freakin' thick and expensive books (if you can afford, LOL) out there and learn by yourself.

Don't ever rely yourself to much on someone else's shoulder to succeed you coz' it's never gonna be worth it to you as well as the person you depend on.

Last but not least, you should be happy there is a guy like Mike who spends his time willingly in writing this "sucky" article for "sucky" guys like you, moreover it's free dammit! Anyway, thx for the writing Mike, I now got something I can hand over to my people, cheers.

7:16 PM  
Anonymous Anonymous said...

Good example. Simple and to the point. No extra BS code. Thanks!

3:04 PM  
Anonymous abdel said...

Well..Well.. Seriously the tutorial simple and have got huge benefit according to the presentation way and smouth understandable.
sorry my english is bad enough, but what i'm trying to say that this tutorial open my eyes to an other way of programming quikly.
Thanks Mike

4:36 PM  
Blogger Luke Agius : - said...

A very good tutorial in my opinion. for newbies who want to understand the technology! IT just did for me. be gratefull that some had to patience to write this.!!

11:35 AM  
Anonymous <a href="users2.titanichost.com/amalopra">JohnBraun</a> said...

HF0YCk write more, thanks.

4:20 AM  
Anonymous Anonymous said...

Thank you so much for such an informative tutorial, it gave me giving me a clear understanding of how AJAX works.

Thank YOu

5:00 AM  
Blogger Administrator said...

Nice good for a newbie to AJAX in .NET.

3:24 AM  
Anonymous Anonymous said...

Well done. Thank you for posting this tutorial. It was the third one I have tried today and it was the only one written clearly enough for me to follow all the way through.

2:01 PM  
Blogger prem said...

Nice Article. You guys have really helped in programming for mediocre programmers who have no choice other than swallowing code of others.

Thanks,

5:53 AM  
Blogger prem said...

Nice Article. You guys have really helped in programming for mediocre programmers who have no choice other than swallowing code of others.

Thanks,

5:54 AM  
Anonymous BusinessLoan said...

This is what I was looking for, thanks for the great lil tutorial!

4:32 PM  
Blogger Rupam said...

yeah, the tutorial is good and I learnt a few new things I never knew about AJAX. Still I require more thing to learn.

Rupam Datta

3:58 AM  
Anonymous Dolly said...

Good one mikey ..thanks:-)

11:27 PM  
Blogger Dilney said...

Thanks. This was very helpful to me as I needed a really simple Ajax solution in .NET!!

2:29 AM  
Blogger Mike Griffiths said...

Take care - this little demo was just supposed to show how simple the AJAX concept is. It was not intended as a practical implementation - although it would work I suppose.

The 2005 and 2008 versions of visual studio have done a lot to introduce effective support for AJAX calls back to the server - could well be worth checking those out.

2:38 AM  

Post a Comment

Links to this post:

Create a Link

<< Home