Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


Javascript Ajax



Ajax is not about XML




How to make the Ajax call

How to make the Ajax call from JavaScript:
  1. Obsolete: XMLHttpRequest object.
    In the early days of Ajax, in vanilla JavaScript you had to construct the XMLHttpRequest object.
    This was complex and verbose. It was hard to make it browser independent.
    I would not recommend this any more.

  2. Works great: Use a library like jQuery.
    In my notes I use jQuery to make the call.
    This makes it much, much simpler than XMLHttpRequest object.

  3. Built-in: fetch.
    jQuery was popular in part because it made Ajax easy.
    Eventually vanilla JavaScript caught up with jQuery and now has "fetch" call.
    See w3schools (and here) and MDN web docs.



Ajax reference

  

jQuery Ajax reference




Javascript Ajax demos

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

Demo HTML JS
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
Ajax demo - parse Flickr XML HTML  



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 ( data )    	// called when request returns in future 
{
 x = data;
 // now can 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.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.