O'Reilly logo

JavaScript Cookbook by Shelley Powers

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

18.3. Determining the Type of Query Call

Problem

You’re not sure whether to send your Ajax call as a GET or a POST.

Solution

For an update, send a POST request. Set the first parameter in the XMLHttpRequest open method to POST, call the setRequestHeader to set the content-type, and send the request parameters in the send method:

xmlhttp.open('POST',url,true);
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlhttp.send(param);

For a query, send a GET request. The first parameter in the XMLHttpRequest open method is set to GET, the parameters are appended on to the URL for the request, and null is passed as parameter in the send method:

url = url + "?" + param;
xmlhttp.open('GET',url,true);
xmlhttp.send(null);

Discussion

What the server component of the application is expecting has the most impact on your request type decision. However, accepted practice is that a request for data should be made with a GET, while an update should occur through a POST.

The request type practice used in Ajax is derived from RESTful guidelines (REST translates as REpresentational State Transfer). According to the guidelines, there are four types of HTTP requests:

GET

Used for retrieving information, with parameters attached to the URL.

POST

Used for creating new data, and parameters are sent via function parameter.

DELETE

Used for deleting data records, and parameters are sent via function parameter.

PUT

Used to send an update, and parameters are sent via function parameter.

There is broad support only for the GET and POST requests at this time, so I’ll focus on these two.

A GET HTTP request is used to retrieve information, and the parameters are attached to the URL in the request. A function that processes a GET request could look like the following, which passes two parameters with the request:

function sendData(evt) {

  // cancel default form submittal
  evt = evt || window.event;
  evt.preventDefault();
  evt.returnValue = false;

  // get input data
  var one = encodeURIComponent(document.getElementById("one").value);
  var two = encodeURIComponent(document.getElementById("two").value);
  var params = "one=" + one + "&two=" + two;

  // prep request
  if (!http) {
     http = new XMLHttpRequest();
  }
  var url = "ajaxserver.php?" + params;
  http.open("GET", url, true)

  // callback function
  http.onreadystatechange=processResult;

  // make Ajax call with params
  http.send(null);
}

In the code snippet, two parameters are passed with the request. First, they’re escaped, using encodeURIComponent. Next, they’re attached to the URL using RESTful GET notation:

http://somecompany.com?param=value&param2=value2

The parameters for the XMLHttpRequest open method are:

GET

A GET request

url

The URL for the service

true

Whether the operation is performed asynchronously

The optional third asynchronous parameter should always be set to true, or the page blocks until the server request returns. This is not a cool thing to do to your page readers.

There are two other optional parameters not shown: username and password. If the application is protected on the server side, the username and password can be used for authentication.

A POST request with two parameters would look like the following:

function sendData(evt) {

  // cancel default form submittal
  evt = evt || window.event;
  evt.preventDefault();
  evt.returnValue = false;

  // get input data
  var one = encodeURIComponent(document.getElementById("one").value).
  replace(/%20/g,'+');
  var two = encodeURIComponent(document.getElementById("two").value).
  replace(/%20/g,'+');
  var params = "one=" + one + "&two=" + two;

  // prep request
  if (!http) {
     http = new XMLHttpRequest();
  }
  var url = "ajaxserver.php";
  http.open("POST", url, true)

  // set up Ajax headers
  http.setRequestHeader("Content-Type",
  "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", params.length);
  http.setRequestHeader("Connection", "close");

  // callback function
  http.onreadystatechange=processResult;

  // make Ajax call with params
  http.send(params);
}

This code differs from the code for the GET request in several ways. The first is that after encoding, the spaces in the parameters are converted from %20 to +. The second is they’re concatenated into a parameter-formatted string, which is sent within the send method.

The first parameter of the open method is set to POST, but the other two parameters are the same as those sent with the GET request: the application URL and the asynchronous flag.

Additional calls are made to the setRequestHeader method, to set Connection and Content-length request headers. You can use it to send any HTTP request header, but you must provide the Content-Type for the POST—in this case, a multipart form request.

Both of the request approaches set the callback function for the Ajax object call’s onreadystatechange event handler.

See Also

Recipe 18.1 covers how to get the XMLHttpRequest object, and Recipe 18.2 covers how to encode parameters.

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