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.
if (navigator.platform != "Win32"
|| (/MSIE \d+\.\d+;/.test(navigator.userAgent)) == false
|| (/Windows NT 5\.0[;\)]/.test(navigator.userAgent)) == false) {
xmlHttp.setRequestHeader("Content-Length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
}
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.
Sena,
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.
<?php
foreach ($_POST as $name => $value) {
echo "$name: $value
";
}
?>
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
I found your comment very usefull to manage both methods easily. Thanks!!
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...
My Ajax works perfectly fine... But my PHP script doesn't want to 'cooperate' :/
'AjaxTmbMerge.php?collapsed=1' -> Target page
In that target-page I wrote:
if(isset($_GET[collapsed])){echo "set".$_GET[collapsed];
if ($_GET[collapsed] == 1){
echo "true";
$collapsed = true;
}else{
$collapsed = false;
}
}else{
echo "Not set";
$collapsed = false;
}
Output: set1
When you click a button it sends 'AjaxTmbMerge.php?collapsed=0' and still it gives 'set1' as output...
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.
cheers
Finally you got me POSTing, I owe you my sanity.
Yaniv
like u are using POST method in AJAX
http.send(body);
Now how u will retrieve this body on server side PHP.
plz help....
You can only post a resource on your same web server it seems.
Someone can fix that?
Thank you!
:P
I created web service using REST.i can run in single machine properly.it is fine.when i send request from one machine another machine using xmlHttpRequest("GET","https://192.168.1.2","false"); the following error occur.
Security Error: Content at https://192.168.1.79/rest/index.html may not load data from https://192.168.1.2?timestamp=1218114764816.
Please give solution
My Ajax works perfectly fine... But my PHP script doesn't want to 'cooperate' :/
'AjaxTmbMerge.php?collapsed=1' -> Target page
In that target-page I wrote:
if(isset($_GET[collapsed])){
echo "set".$_GET[collapsed];
if ($_GET[collapsed] == 1){
echo "true";
$collapsed = true;
}else{
$collapsed = false;
}
}else{
echo "Not set";
$collapsed = false;
}
Output: set1
When you click a button it sends 'AjaxTmbMerge.php?collapsed=0' and still it gives 'set1' as output...
ajaxObj.onreadystatechange = 'ajaxStdCb';
Instead of
ajaxObj.onreadystatechange = ajaxStdCb;
So my callback was a string and couldn't be converted :P
Thanks a lot for your help :)
-----------------------
// POST的方式傳值
var url = path+'(GetLineData)?openagent';
var params = 'Path='+path+'&DItem=' + ditem+'&DChange_Date='+dcdate+'&DCurrency='+dcurrency+'&DIn_Account='+dinaccount+'&DOut_Account='+doutaccount+'&DAmount='+damount+'&DChk='+dchk+'&DRmk='+drmk ;
http.open("post", url, true);
.
.
.
http.send(params);
-----------------------
I used Query_String_Dec to received params(as below)
-----------------------
Dim wdoc As NotesDocument
Set wdoc=session.DocumentContext '目前網頁文件
Dim Subkind As String
subkind=wdoc.Query_String_Decoded(0)
------------------------
If that params data is too large than did't show the right data in my result page,
Any body can help?
i am learning ajax now,
I have a problem in ajax calls
Here is the description of my problem,
I have search form which searches for the names in database,
If i have searched for the first time onsubmit() in the form it will go and call the ajax
function and establishes and fetches the data correctly
After that i want to refine my search but it was not fetching the data from the other page
If i have checked the xmlrequest.readyStatus it is showing '1' for the subsequent calls
can any body help on this.
Thanks & Regards
Hari
Thanks a lot for your article.
Jurandi
correct : http.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
incorrect: http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Thanks for that buddy.. i was having difficulty not knowing why POST didn't work with the HTTPRequest...
It was because i wasn't sending the headers along with it.. just the form, which IIS didn't assume was a form and so my Form variables were always empty!
Thanks
Dan
<form action="form_handler.php" method="post">
<label id="el1">
<select name="selVar" id="selVar" onFocus="javascript:callOptionList(this,'el1',1);">
<option value="defaultValue">defaultValue</option>
</select>
</label>
</form>
now when focus is placed on the select box it will be replaced with a really big select list like 500 options one of the reasons why I used ajax to do this.
Becomes like this after the ajax call.
<form action="form_handler.php" method="post">
<label id="el1">
<select name="selVar" id="selVar">
<option value="v1">v1</option>
<option value="v2">v2</option>
<option value="v3">v3</option>
<option value="v4">v4</option>
<option value="v5">v5</option>
<option value="v6">v6</option>
<option value="v7">v7</option>
<option value="v8">v8</option>
<option value="v9">v9</option>
<!-- and so on ... -->
</select>
</label>
<input type="submit" name="Submit" value="Update">
</form">
Now when the submit button is clicked I no $_POST['selVar'] is past. But this works fine in IE 7.0
Does anyone has the same problem or know how to fix this issue? ...Or is it just een Firefox bug?
That might fix it.
Thanks
Thanks.
Thanks, for you tutorial, but i can't make it send the parameters. Here's my code :
function makeAjaxRequest(method, ajax, url, params)
{
method = method.toUpperCase();
if (method == 'GET')
{
para = encodeURI(params);//encode special chars in url
ajax.open("GET", url+'?'+para, true);
ajax.send(null);
}else if (method == 'POST')
{
para = encodeURI(params);
ajax.open("POST", url+para, true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.setRequestHeader("Content-length", para.length);
ajax.setRequestHeader("Connection", "close");
ajax.send(para);
}else
{
return false;
}
}
makeAjaxRequest("POST", ajax, "./index.php", "page=M_articles_manager&mpage=postArticle&text=popopo&title=uiui");
It works perfectly with GET, but with POST i always get the code of the current page as a response, exactly as if the params where "".
Thanks in advance.
Hai I got few points from this which is very useful. Thanks. I have a doubt.
I used AJAX for a simple project. In that I used the following statement.
xmlHttp.open("POST",edit_company_ajax.php+"?flag="+flag+"&user="+user_id,true);
xmlHttp.send(null);
When I executed this code in my browser it is working fine. But when I executed the same in my friends system I got the following error message.
------------------------
While trying to process the request:
POST /~lakshmanan/13_deploy/Trainee_FinalProject_2007/lakshmanan_sathishkumar/bin/edit_company_ajax.php?id=1 HTTP/1.1
Host: 192.168.1.12
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.3) Gecko/20070310 Iceweasel/2.0.0.3 (Debian-2.0.0.3-1)
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://192.168.1.12/~lakshmanan/13_deploy/Trainee_FinalProject_2007/lakshmanan_sathishkumar/bin/Edit_company.php
Cookie: PHPSESSID=334e96eccb310ebe8acc545ea626f122
Pragma: no-cache
Cache-Control: no-cache
The following error was encountered:
* Invalid Request
Some aspect of the HTTP Request is invalid. Possible problems:
* Missing or unknown request method
* Missing URL
* Missing HTTP Identifier (HTTP/1.0)
* Request is too large
* Content-Length missing for POST or PUT requests
* Illegal character in hostname; underscores are not allowed
---------------------------------------
Now I changed my code to GET method.
xmlHttp.open("GET",edit_company_ajax.php+"?flag="+flag+"&user="+user_id,true);
xmlHttp.send(null);
It is working fine in my friends system.
I wanted to know why the problem occurred in my friends system and why it is worked in my system?
pls help.
Params are constructed and passed as value to send method
Anyone has faced this issue
ajaxReq.onreadystatechange = populate;
ajaxReq.open("POST", url, false);
ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.send(param);
vladimir.skach.cz/sanandreas/download.php?filename=063_key_to_her_hearth.zip&name=Key%20To%20Her%20Hearth
if you want to see all $_POST, use
<?php
print_r($_POST);
?>
You may also see $_GET or $_REQUEST etc
third argument,I know this 4 aschynchronus and synchronus communication,what is this,how it will work,if
i changed true or false.can u explain to me ...
I wonder if anybody knows what firefox 3 & chrome is doing to make it work and if that can be duplicated in my javascript where I make the POST call so it will work in IE7 as well.
In the mean time, guess I am stuck will all the limitations of GET.
* potential reply to last annon
I wonder if anybody knows what firefox 3 & chrome is doing to make it work and if that can be duplicated in my javascript where I make the POST call so it will work in IE7 as well.
In the mean time, guess I am stuck will all the limitations of GET.
* potential reply to last annon
Reply to this.
How can I do this??
My class is (funnily enough!!!) call AJAX, aside from various setter / getter methods is a final runAjax called from the page which includes its own instance:
var example=new Ajax();
//other code
example.runAjax(example);
then in the class:
Ajax.prototype.runAjax=function(pageobj){
this.xmlhttp.open("GET", this.url+"?"+this.data, true);
this.xmlhttp.onreadystatechange = function(){
pageobj.ajaxDone();
}
this.xmlhttp.send(null);
}
Ajax.prototype.ajaxDone=function(){
//Run after AJAX completion
if(this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200){
alert(this.xmlhttp.responseText);
}
}
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.