How to Handle the Response from the Server in Ajax

  • google plus

In Brief...

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.

Instructions

  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 Training

Categories

Courses

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss