Using POST method in XMLHTTPRequest(Ajax)
Usually only the GET method is used while creating Ajax apps. But there are several occasions when POST is necessary when creating a ajax request. This could be for several reasons. For example, POST request are considered more secure than GET request as creating a POST request is relatively harder than creating a GET request.
Requirements
- Create a XMLHTTPRequest Object that uses the POST method.
- See if the arguments passed to it appear in the '
$_POST' array in PHP.
Code
XMLHTTPRequest Object
For the sake of simplicity, we are going to create the XMLHTTPRequest object using the Firefox supported ' XMLHttpRequest()' function. I believe that you know the proper way of creating a cross-browser XMLHttpRequest object. If not, learn that first.
var http = new XMLHttpRequest();
Using GET method
Now we open a connection using the GET method.
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
I really hope that this much is clear for you - I am assuming that you know a bit of Ajax coding. If you don't, please read a ajax tutorial that explains these parts before continuing.
POST method
We are going to make some modifications so POST method will be used when sending the request...
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);
The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument - in the GET method, we send the parameters along with the url separated by a '?' character...
http.open("GET",url+"?"+params, true);
But in the POST method we will use just the url as the second argument. We will send the parameters later.
http.open("POST", url, true);
Some http headers must be set along with any POST request. So we set them in these lines...
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
We set a handler for the 'ready state' change event. This is the same handler we used for the GET method. You can use the http.responseText here - insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.
http.send(params);
Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as "lorem=ipsum&name=binny" - so we send two parameters - 'lorem' and 'name' with the values 'ipsum' and 'binny' respectively.
That's it. If you wish to see the working of this script, I have set up a demo page for Ajax using post.
Libraries
The above given methods are the manual way of doing things - you can automate this using the hundreds of Ajax libraries out there.
jx
jx.load("get_data.php?lorem=ipsum&name=binny",handlerFunction,"text","POST");
Prototype
var myAjax = new Ajax.Request('get_data.php?lorem=ipsum&name=binny',{
method: 'post',
onComplete:handlerFunction
});
Dojo Toolkit
dojo.io.bind({
url: "get_data.php?lorem=ipsum&name=binny",
mimetype: "text/plain",
method: "POST",
load:handlerFunction
});
Yahoo! UI
var myAjax = YAHOO.util.Connect.asyncRequest('POST', 'get_data.php?lorem=ipsum&name=binny', {success:handlerFunction},"");
Mochikit
var ajmyAjax = doSimpleXMLHttpRequest('get_data.php?lorem=ipsum&name=binny').addCallback(handlerFunction);

Comments
This is about using Method POST
Good stuff u got that!
Quite helpful
On the bright side of GET is that you can scour IIS logs and see what data is being passed. This is great for troubleshooting or recovering data. No such luck with POST.
i have a query: may be it is a drawback in ajax
i want to get the responseText( query string) values from php code, how to get thoses values in php?
thanks and regards
ashok@web2ph.com
Thanks,
Cheers!!
Thank in advance.
Hope this help someone see a potential answer.
Thanks.
When I do a POST, it takes nearly 3-4 minutes for the http.readyState to become 4. Is there any way to optimize this?
Please respond ASAP.
-Jay
Note: Paul wrote there above about some benchmark he did using GET VS POST, well I must notice that in my tests I had different results.. POST didn't take that long to process my requests. Well maybe he had some misconfiguration at his browser (just a hint).
Ps.: I'm Brazilian, so I excuse about my poor eglish .. hope to be understandable.
Best regards,
Leonardo Todeschini
Alcatel-Lucent (Brazil)
Mail: leotodeschini@gmail.com
TIA
im from indonesia.
i needed to get the value with the getParameter() of the servlet java API. You found the key ;)
Thanks!
prodotti-tipico.blogspot.com/ rel="nofollow">prodotti tipico*
homeward this seems not like reality but like one of the sharp
Anyone have a similar problem? any help is greatly appreciated,
Josh T.
Thank you.
till i found out that _GET's are cached....grrrrrr (FIST).
OFC i needed to swtich to POST, and i found your site on google. thanks for the header info :)
saves me lots of time.
now if only the fact that GETs were cached was higher on the google ranking...
Thank you
your post help me a lot.
I really dint have to run around here n there for the info!
Thanks!
var fmtext = document.getElementById('fmfield').value;
then changed var params = "newtext=fmtext";
only the text fmtext is being posted rather than the variable.
can anyone please tell me what is wrong?
var params = "newtext=" + fmtext;
I have used ur method as u written but still i m geting proper responce.
can u help me out.
Isn't the post parameters just being revealed in the js code? I didn't understand that part. If I wanted to validate a password against a php file...how would I use POST method? If the params have to be set in the JS code? I think I am missing something here...
But how can i use it with form. I mean what code do you need to use ajaxPost after pressing the submit button in a form.
and when you use the 'POST' method, and when your param is empty, you shouldn't use send(null), you should use send("") instead.
after using this code i m getting above error plz help me
thnks in advance
Anonymous at 28 Sep, 2007 12:00
nsIXMLHttpRequest.setRequestHeader error in Gecko...
Make sure you call the xhr.open().... before calling xhr.setRequestHeader.
This damn thing bugged me for some time. And if I ommited the setRequestHeader I was unable to access my $_POST array on the PHP server. PHP 5.2.5.
developer.mozilla.org/en/docs/nsIXMLHttpRequest
Near the bottom quarter of the page.
Hope this keeps other from wasting too much time.
I was lookin for the same stuff.... after referring to this article i got my problem solved....
HTH,
Steve
Regards,
Joshua
FYI: In Javascript, the function escape() does the same as urlencode() in PHP (solution to the above '+' question but look at this page first http://cass-hacks.com/articles/discussion/js_url_encode_decode/)
I DON'T WANT AJAX TO SEND ANY INSTRUCTION TO ".ASP" OR ".PHP" FILE.
AS I DON'T KNOW ASP & PHP SCRIPTING.
I AM JS EXPERT BUT AJAX NEWBIE.
CAN U TELL ME WAY HOW CAN I INTERACT WITH XML FILE DIRECTLY WITHOUT USING ".ASP" OR ".PHP" FILE.
THX FOR READING
Hope it helps someone
var url = "get_data.asp"; // I'm using asp, hence i change to asp extension
var params = "lorem=ipsum&name=binny";
hence, in get_data.asp, how can I retrieve the lorem and name value ?
can I request.querystring("lorem") and request.querystring("name") ? but this is not GET method
Also can I use request.form("MyOtherField") that not in params ? or I can only input everything into params, and then request.querystring to retrieve the value ?
Please advise. Thank you.
E.g.
???
e.g.
var params = "lorum=" + encodeURIComponent(someLongString);
?
Its working fine in W2k ff, IE6, IE7...
Not working only in W98 & WNT ff.
On click of a link, I am trying to log some details asynchronously.
98 & NT ff not able to send this request. If i send it synchronously its working.
Is there any fix for this?
Thanks in advance for any help.
Prabha.
var url = "data.php?people=" + encodeURIComponent(document.getElementById("people").value);
How do we handle "body" in PHP
Saved my ass.
I ussually use : ereg_replace("\n","
",$_GET/POST[textarea]) when showing a message input. (I am PHP Mania)
I think POST method can solve this problem.
Please help...
http.open("POST",URL,TRUE,username,password)
thanks in advance.
Since this is essentially constructing a string and passing it in a post format, is there a functional limit to it's size?
I have several dozen fields to capture and using the jscript function to rip the data from each field and append to the post string seems clumsy. Is there an alternative like the form submission that takes all the inputs and combines them by name into dollar_POST?
What is the value I havev to give for username and password? Cant we work without username and password?
Thanks in advance.
What is the value I havev to give for username and password? Cant we work without username and password?
Thanks in advance.
But if you use http post, its ok.
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.