Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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

How it works…

The XMLHttpRequest class has two methods you use to make a request: open and send. You use the open method to start the process of issuing the request, and the send method if you need to send data (say, with a POST...