Making an asynchronous request for data

You use the instance of the XMLHttpRequest class you created to request data. You can request data using any HTTP method; typically you'll use GET or POST. GET is good if you don't need to pass any arguments, or if the arguments are encoded in the service URL; POST is necessary if you're going to post JSON to the server as arguments for your server-side script.

How to do it...

Continuing to enhance our client page script's doAjax function, here's how to issue an asynchronous request, modifying the previous example:

function doAjax() {
  var xmlhttp;
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=newXMLHttpRequest();
  
    xmlhttp.open("POST","/", true);
    xmlhttp.send("");
  }
}

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.