How to Handle the Response from the Server in Ajax

See Ajax: Tips and Tricks for similar articles.
Looking to improve your Ajax skills? Check out Webucator’s Ajax classes.

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.

  1. Create an XMLHttpRequest object 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");
            
  2. To detect the response, look for a change in the state of the xmlhttp response, using the onreadystatechange event handler.
    xmlhttp.onreadystatechange = function() {
        //Do something here
    }
                
  3. Write a callback function to do something when the state of the response changes.
    xmlhttp.onreadystatechange = function() {
        console.log("Ready State: " + xmlhttp.readyState);
    }
                
  4. Use the send() method to send the request.
    xmlhttp.send();

Related Articles

  1. How to Make a Cross-origin Ajax Request
  2. How to Create a Login Form with Ajax
  3. How to Set Up Automatic Session Timeout with Ajax
  4. How to Use the Callback Function in Ajax
  5. How to Develop a Web Application with Ajax
  6. How to Make GET, POST, and HEAD Requests Using Ajax
  7. How to Use the jQuery ajax() Method
  8. How to Create a Lookup Form with Ajax
  9. How to Create a Slideshow with Ajax
  10. How to Handle the Response from the Server in Ajax (this article)
  11. How to Set Up for Ajax Training on Windows
  12. Inline Editing Using Ajax
  13. How to Create a Navigable Table with Ajax