Javascript Ajax
- Ajax
- Variety of methods of building fully user-interactive web applications.
- Features:
- Ajax is usually based on Javascript.
- Javascript can communicate with server constantly in background.
(In response to user action on client side, or just on timer, etc.)
- e.g. User is picking a userid. As he types, Javascript sends communication (HTTP requests) to server in background
to check server database to see if userid is free.
- Small parts of the page can change after initial loading,
rather than entire page being re-loaded.
- Examples:
- XMLHttpRequest - the API to do this.
Ajax is not about XML
- Ajax is badly named.
- It stands for "Asynchronous JavaScript and XML".
- When it emerged, XML was the normal expected return data.
- But in fact, and despite the name "XMLHttpRequest", the return data does not have to be XML.
- JSON return data is common, and some people call it
"AJAJ"
when they do that
("Asynchronous JavaScript and JSON").
- e.g. Flickr XML and JSON feeds
How to make the Ajax call
How to make the Ajax call from JavaScript:
- 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.
- 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.
- 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.
Vanilla JS
jQuery
Simple pages.
No header or footer.
To make it easier to View Source.
Note source loads jQuery.
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