The roundtrip that is involved with this process can make the server appear sluggish. It can also be tedious for the server to have to try to remember all the form data that was entered by the user. In fact you have probably noticed that many web sites simply forget the data that you entered and make you re-enter it, something I find incredibly annoying.
With Ajax Javascript is able to send a request to the server without submitting the entire form. The user is able to continue working with the form while the server processes the result. When the server is done it sends the result back to Javascript and Javascript can appropriately update the form, without having to re-load the entire page. Because the requests are asynchronous, Javascript can have multiple requests outstanding at any given time.
// this code courtesy of Adam Thompson var ajaxreq = null; if( window.XMLHttpRequest ) { ajaxreq = new XMLHttpRequest(); } else if( window.ActiveXObject ) { ajaxreq = new ActiveXObject( "Msxml2.XMLHTTP" ); if( ajaxreq == null ) { ajaxreq = new ActiveXObject( "Microsoft.XMLHTTP" ); } } if (ajaxreq == null) alert("Your browser does not support AJAX!");
ajaxreq.open("GET", "search.php?query=John");
ajaxreq.open("GET", "search.php?query=John"); ajaxreq.send(null); ajaxreq.open("GET", "foo.xml"); // opening xml file so no params needed ajaxreq.send(null); ajaxreq.open("POST", "search.php"); // using POST so must pass param string ajaxreq.send("query=John");
value | meaning |
---|---|
0 | new request |
1 | open has finished--the request has been initialized |
2 | send has finished--the request has been sent |
3 | the server is working on the request |
4 | the request is complete |
function responseHandler() { if (ajaxreq.readyState != 4) return; if (ajaxreq.status == 200) ajaxreq.callback(); else alert("Ajax error code " + ajaxreq.status + ": " + ajaxreq.statusText); } ... ajaxreq.onreadystatechange = responseHandler; ajaxreq.callback = yourCallbackFct;