COMP 20: Web Programming
What is Ajax?
- All of our web programs have been of the response-request model (circa late 1990s). In other words, there is a lot of waiting! Thus, causes usability issues
- Why can't web applications be more like desktop applications (i.e., as fast)?
- Not a programming language
- The big ideas:
- No more waiting around!
- Only update a certain section of a page at a certain time with data from a server-side script (most of the times from the same domain and some times from a different domain)
- The asynchronous process:
- You continue to work on the page
- The server's response has only the data the page needs --without any markups
The Core of Ajax: The
onChange in a text box
XMLHttpRequest requests a document from the web server
- Server retrieves data, sends it back
- Ah ha,
XMLHttpRequest fires event saying that data has arrived
- A handler function is necessary to receive the notification...
- ...and to process the data. Update the display typically using the DOM
open(method, url, asynchronous? (true or false))
send(data string) - start it up! Usually send
null as data string
onreadystatechange - Set this to the handler function (when request is complete)!
readyState - A number indicating what state the request is in:
- 0 => Not initialized
- 1 => Set up
- 2 => Sent
- 3 => In progress
- 4 => Complete
- A change in
onreadystatechange handler function runs
responseText - The response data
responseXML - The response data as a document tree
status - The HTTP status code returned from the server
- Q: Can ready state = 4 but you receive errors? How do you account for this?
Important! Security Restrictions
- Cannot open files on your own machine (i.e.,
- You can fetch files from a different web server --if the server-side script on the different web server has enabled Cross-Origin Request Sharing (CORS)
Question: Does a readyState of 4 always mean a good thing?