Making POST request with XMLHTTPRequest
Overview
I was debugging on a Web App with AJAX features, situation was that one of the AJAX call fails when too many items (values) are passed to server side. By looking at the JavaScript I saw that “GET” method was used to make the AJAX call with XMLHTTPRequest object. Knowing that “GET” method have a size limit (indeed that is a URL length limit), I tried using “POST” method instead.
But this time I found that the Query Parameters were not received at server side. With some googling I found an article at OpenJS about making AJAX call by “POST” method. The key point is that AJAX “POST” request needs specific HTTP header fields in order to work properly.
Reference
Using POST method in XMLHTTPRequest(Ajax)
WWW FAQs: What is the maximum length of a URL?
Steps
Code Snippet (Copied from Reference 1)
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Discussion
What do you think? Leave a comment. Alternatively, write a post on your own weblog; this blog accepts trackbacks [trackback url].
Leave a Reply