How to Handle the Response from the Server in Ajax

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();
Author: Chris Minnick

Chris Minnick, the co-founder of WatzThis?, has overseen the development of hundreds of web and mobile projects for customers from small businesses to some of the world’s largest companies. A prolific writer, Chris has authored and co-authored books and articles on a wide range of Internet-related topics including HTML, CSS, mobile apps, e-commerce, e-business, Web design, XML, and application servers. His published books include Adventures in Coding, JavaScript For Kids For Dummies, Writing Computer Code, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW E-Commerce Designer Certification Bible, and XHTML.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.