SearchSearch   MemberlistMembers   RegisterRegister   ProfileProfile   Log inLog in 

Ajax "Hello World" Example

 
Post new topic   Reply to topic    Open Hosting Internet Solutions Forum Index -> Articles and Tutorials -> General Web Development
View previous topic :: View next topic  
Author Message
Nick
Forum Moderator


Joined: 18 Jun 2002
Posts: 3635

PostPosted: Mon Mar 27, 2006 5:33 pm    Post subject: Ajax "Hello World" Example Reply with quote

Ajax "Hello World" Example

An introduction to what Ajax is and a basic "Hello World" example. Includes a downloadable example and suggests areas for further examples.

What is Ajax?
There's a growing momentum behind newly-launched websites at the moment. Part of the rise of the Web 2.0 concept has been the mainstream adoption of AJAX (Asynchronous JavaScript And XML). Ajax isn't anything new, nor are the technologies behind the name, but they've found a new lease of life on trendy new sites. So what is Ajax exactly? Put very simply, it's a combination of XHTML, CSS and most importantly JavaScript and XMLHttpRequest that allows you to update your web page content without refreshing the page.

Of course, this is an over-simplified example and the funtionality of the Ajax technologies has a far wider scope. But this article will show you the bare structure of an Ajax-type request, and will show you how to use it on your own site.

The Code
The XMLHttpRequest object effectively allows you to GET or POST to a remote script using JavaScript. In our example we will use this object to open a text file and read back its contents. The code that follows creates an XMLHttpRequest object ready for us to use. We check for Internet Explorer since IE uses its own XMLHttpRequest object that is different from other browsers. When the page loads, the createRequestObject function is called and an instance of the XMLHttpRequest object is stored in the variable "http".
Code:
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
   var objAjax;
   var browser = navigator.appName;
   if(browser == "Microsoft Internet Explorer"){
      objAjax = new ActiveXObject("Microsoft.XMLHTTP");
   }else{
      objAjax = new XMLHttpRequest();
   }
   return objAjax;
}

function getNewContent(){
   http.open('get','newcontent.txt');
   http.onreadystatechange = updateNewContent;
   http.send(null);
   return false;
}

function updateNewContent(){
   if(http.readyState == 4){
      document.getElementById('mySentence').innerHTML = http.responseText;
   }
}
</script>


The second function should be called from a page element, such as a hyperlink or a button. This element will trigger the Ajax event (getNewContent), which reads the content text file. The third and final function (updateNewContent) checks the result of the XMLHttpRequest and updates the page accordingly.

A Hello World example
The JavaScript above should be placed within your HTML page, or included as an external .js file. You should create a text file named "newcontent.txt" containing the words "Hello World" and save it in the same folder as your HTML page. Your event trigger element should call the second function, like this:
Code:
<p id="mySentence">
<a href="#" onclick="javascript:getNewContent();">Click here to update the page</a>.
When you click the link, this content will be replaced.</p>


When the link is clicked, the getNewContent function is triggered. It calls a text file named "newcontent.txt". The function updateNewContent monitors the progress of the request, and when it is complete, the HTML element with an id of "mySentence" is updated with the text file contents.

Try out a live example!

Download all files as a Zip file
To make things a bit easier, you can also download the live example and all code referenced in this article as a Zip file.

Further applications
This is the simplest Ajax example I could think of. If you want to make the "Hello World" content dynamic, you can use the code to request an ASP or PHP page rather than a text file. With some simple modification you could pass some parameters to this request and start to interface with a database. In its most complex form, Ajax has been used to build entire interfaces. Gmail and Google Maps for example, use Ajax heavily to create navigation and page content without refreshing the entire browser page. On your own sites it is likely that you will find Ajax useful for the following common features:
  • Validating form fields
  • Auto-complete form fields
  • Updating content based on timers (e.g. an auction)
  • Performing real-time spell checking of form fields
  • Dynamically loading list/select boxes based on other form choices


Benefits of using Ajax
  • Just a small section of a page can be updated without having to reload the entire page. This saves on bandwidth and loading times, and reduces server load.
  • The code is lightweight and not very complex.
  • JavaScript and the XMLHttpRequest object are supported in all modern browsers
  • It's got the geeky cool factor Wink


Potential disadvantages of using Ajax
  • Not everybody has JavaScript enabled in their browser (by choice, or otherwise). You should make sure that your site functionality does not require Ajax and that the site is usable without the Ajax fanciness
  • Breaks the back button. Try the example above and click the back button. The original content isn't replaced, as a normal page in your History is. Therefore you should make plans for a function to also reverse any content replacement if necessary
  • If content is embedded within JavaScript code then this can reduce the effective accessibility of your site.


Last edited by Nick on Mon Mar 27, 2006 8:13 pm; edited 4 times in total
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Mark Voss
Divine Being


Joined: 19 Jun 2002
Posts: 4946
Location: Cardiff, UK

PostPosted: Mon Mar 27, 2006 6:57 pm    Post subject: Reply with quote

I recently wrote something simailar that pulled in an asp page which was updated every 30 seconds or so.

It worked fine in Firefox but in IE the content wasn't updated after the first 'click' of the button unless IE was set to 'Check for newer versions of stored pages' on 'Every visit to the page' rather than the default 'Automatically'.

To get round this I had to add a random querystring to the asp page so, instead of using:

Code:
http.open('get','newcontent.asp');

I used the random() method of the Javascript Math object to add the random querystring:

Code:
http.open('get','newcontent.asp?id='+Math.random());

_________________
Mark Voss
http://www.markvoss.net


Last edited by Mark Voss on Sat Apr 08, 2006 10:13 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
Nick
Forum Moderator


Joined: 18 Jun 2002
Posts: 3635

PostPosted: Mon Mar 27, 2006 7:51 pm    Post subject: Reply with quote

Would it work if you added some no-cache headers to the ASP page?
Code:
<%
Response.Expires = 60
Response.ExpiresAbsolute = Now() - 1
Response.AddHeader "pragma","no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"
%>

That said, I've found the random querystring method to work fine in the past.
_________________
Nick Dunn
Nick Dunn
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Mark Voss
Divine Being


Joined: 19 Jun 2002
Posts: 4946
Location: Cardiff, UK

PostPosted: Thu Mar 30, 2006 9:06 am    Post subject: Reply with quote

Yes - by adding just:
Code:
<%
Response.CacheControl = "no-cache"
%>

to the 'pulled' asp page (newcontent.asp) the content refreshes properly Smile

So now we have two methods of getting this to work in IE with dynamic content:
One on the 'pulling' page and one on the 'pulled' page.
_________________
Mark Voss
http://www.markvoss.net
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    Open Hosting Internet Solutions Forum Index -> Articles and Tutorials -> General Web Development All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.11 © 2001, 2002 phpBB Group
FAQClick here for help using the phpBB forum