- Variety of methods of building fully user-interactive web applications.
(In response to user action on client side, or just on timer, etc.)
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.
- XMLHttpRequest - the API to do this.
Ajax is not about 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
when they do that
- e.g. Flickr XML and JSON feeds
I remove the header and footer to make it easier to View Source.
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 say:
string x = makeRequest(url); // get back string
// do stuff with x ...
Instead you do:
// .. don't do anything with x yet
function fn() // called when request returns in future
string x = // .. get return value
// now can do stuff with x ...
// and you may need multiple lines like this throughout the code:
if ( x ) .....
// there is uncertainty in code if x exists yet or not
XHR2 - Cross-origin Ajax
- XMLHttpRequest Level 2 (XHR2)
- Cross-origin resource sharing (CORS)
- Standard for allowing controlled cross-origin Ajax.
- Server must co-operate.
Server returns HTTP response headers.
(e.g. It is easy for PHP to output a response header before payload.)
Allow one site:
Allow all sites:
XHR2 with CORS probably better solution than JSONP.
Can retrieve any data format.
Better error handling.
- Need server to send headers though.
e.g. At time of writing, Flickr does not.