O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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("");
  }
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required