Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

My big idea: Ancient Brain


CA114      CA170

CA668      CA669      Projects

Javascript Ajax

Ajax is not about XML


Browser-independent code

Javascript Ajax standards have varied across browsers. Can be tricky to write browser-independent, backward-compatible code.

One solution is to use other people's Javascript libraries/frameworks to take care of this complexity for you.

Use jQuery

Javascript Ajax demos

Simple pages. No header or footer. To make it easier to View Source.
Note source loads jQuery.

Ajax demo - fetch server file HTML JS
Ajax demo - fetch server file (minimal) HTML  
Ajax demo - call server program HTML JS
Ajax demo - call server program (minimal) HTML  
Ajax demo - fetch XML and parse HTML JS

Asynchronous programming

Coding Ajax takes some getting used to, because it is asynchronous.
You fire off a HTTP request. And then your code carries on.
At some future point the HTTP request returns.
When you make the request, you include the future function to call.

So you can't do:

var x = makeRequest(url);  // get back data
// do stuff with x ...
Instead you do something like:
var x;
makeRequest(url, fn); 
// .. don't do anything with x yet

function fn()	// called when request returns in future 
 x =  // .. get return data
 // now do stuff with x ...

// and you may need multiple lines like the following in other parts of code:

 if ( typeof x == 'undefined' ) ...   // x has not yet been defined  
 else ...                             // x is defined

ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.

Wikipedia: Sometimes I link to Wikipedia. I have written something In defence of Wikipedia. It is often a useful starting point but you cannot trust it. Linking to it is like linking to a Google search. A starting point, not a destination. I automatically highlight in red all links to Wikipedia and Google search and other possibly-unreliable user-generated content.