You may want to understand a bit more about how Ajax works.
What readystates are
This might help you to understand how XMLHttpRequest works.
Add these lines to the second function (handleReply) before the IF:
var state=request.readyState;
alert(state);
var text=request.responseText;
alert(text);
Each time the state of the connection between the server and the browser changes you will get two alert boxes which tell you the new state and the text of the response from the server (which will be null at first). Only with readyState 4 does the text get placed into the Web page. The response states are:
- 0 - unsent - the connection has not been used to send a request (uninitiated)
- 1 - opened - the connection exists and send() can now be used to send the request
- 2 - HTTP headers received by the server (the URL in this case)
- 3 - loading (the response is being received)
- 4 - the response has been received and either data or an error message should be available
AJAX and XMLHttpRequest are new technologies so be prepared for changes but this seems fairly settled.
User-entered data
The example code needs to be changed slightly if you plan to use it on a real page. This is because the data to be sent using GET might include some reserved characters (spaces, ampersands, the plus sign and the equals sign are all either not allowed or have special meaning when used in a URL/URI). Whenever using user data and Ajax make sure the data is encoded safely by using encodeURIComponent:
xmlrequest.open("GET",'autocomplete.php?content='+encodeURIComponent(document.getElementById('fred').value),true);
You will also need to protect against SQL injection and other security issues in the PHP page as you always must when processing user data.
Error handling
In addition to the usual use of alert boxes to check what is going on you can use the HTTP headers to be sure if everything is OK. When a page is requested from a server it also sends a code with the page (or other data) which comes back to the browser. A 200 code means the page was sent properly. 400 codes mean a problem with the page (not found or you do not have access rights). 500 means the server has a problem. You can check the status header and use IF statements to handle errors within the JavaScript:
var htmlheaderstatus=xmlrequest.status;



