- The oddly-named Javascript XMLHttpRequest object allows Javascript to
send its own HTTP request to a server, and collect the response.
- The Javascript can then update the page with the data from the server.
- This technique goes by the name AJAX, for
“Asynchronous Javascript and XML,” even when no XML is involved.
- Here is a simple AJAX [chat pageSource]
- Do go ahead and try it, especially during class so you'll have
someone to talk to. Enter any handle you like, a message, and send it.
- When you send a message, the Javascript makes an HTTP request to
a PHP script on the server to deliver the message.
- The PHP script stores it in a file.
- The Javascript keeps its message area up to date by polling the
server twice a second to request new messages.
- Messages are numbered internally. The Javascript remembers the
number of the last message it received, and asks for all newer ones.
- On the server side is this
AJAX [message exchange scriptSource].
- It does not generate or send HTML and is not intended to be visited
in a browser.
- It generates either plain text or JSON.
- The PHP accepts messages from the Javascript which are sent as request
data, and stores them in a file. It responds with just a plain text
OK or error message.
- It accepts polls and responds with an error or a JSON document
reporting any requested messages. (This could be zero messages.)