How to Handle the Response from the Server in Ajax
See Ajax: Tips and Tricks for similar articles.
Because Ajax calls are asynchronous, we can't be sure when the response will come, so we must write code to wait for the response and handle it when it arrives.
- Create an
XMLHttpRequestobject and make a request. Learn how to create one here.var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","http://www.example.com/Demo?FirstName=Chris&LastName=Minnick"); - To detect the response, look for a change in the state of the
xmlhttpresponse, using theonreadystatechangeevent handler.xmlhttp.onreadystatechange = function() { //Do something here } - Write a callback function to do something when the state of the response changes.
xmlhttp.onreadystatechange = function() { console.log("Ready State: " + xmlhttp.readyState); } - Use the
send()method to send the request.xmlhttp.send();
