The second most common type of HTTP request is a POST. Typically, POST requests are used when entering data into a Web form because they are capable of sending much more data (around 2 GB) than GET requests.
Just like a GET request, the parameters for a POST request must be encoded for use in a URL and separated with an ampersand, although the parameters aren’t attached to the URL. When sending a POST request, you pass in the parameters as an argument to the send()method:
oRequest.open(“post”, “page.php”, false); oRequest.send(“name1=value1&name2=value2”);
It also helps to have a function for formatting the parameters for a POST request:
function addPostParam(sParams, sParamName, sParamValue) { if (sParams.length > 0) { sParams += “&”; } return sParams + encodeURIComponent(sParamName) + “=” + encodeURIComponent(sParamValue); }
This function is similar to the addURLParam()function, although addPostParam()deals with a string of parameters instead of a URL. The first argument is the existing list of parameters, the second argument is the parameter name, and the third is the parameter value. The function checks whether the length of the parameters string is longer than 0. If so, then it adds an ampersand to separate the new parameter. Otherwise, it returns the parameter string with the new name and value added. Here’s a brief example of its use:
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
oRequest.open(“post”, “page.php”, false);
oRequest.send(sParams);
Even though this looks like a valid POST request, a server-side page expecting a POST actually won’t interpret this code correctly. That’s because all POST requests sent by a browser have the “ContentType”header set to “application/x-www-form-urlencoded”. Fortunately, that can be easily corrected using the setRequestHeader()method:
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
oRequest.open(“post”, “page.php”, false);
oRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
oRequest.send(sParams);
Now this example works just like a form POSTed from a Web browser.