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

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

Anonymous at 13 Nov, 2006 09:02
Hello,
This is about using Method POST
Reply to this.
Anonymous at 15 Nov, 2006 10:55
I actually used this to help me with using the MSXML library within MS Access 2003. I could do a GET just fine, but the POST was eluding me. This showed exactly what I needed, how to transform my GET into a valid POST. THANKS A TON!!!!
Reply to this.
Anonymous at 23 Jan, 2008 11:44
have you found the solution? I met the same problem as you.
Reply to this.
Anonymous at 25 Jan, 2009 09:58
Same here, the content type is that missing piece for me.
Reply to this.
Anonymous at 06 Dec, 2006 03:59
I was missing the http header info...banged my head on the wall for quite a while on that one. Thanks!
Reply to this.
Anonymous at 07 Dec, 2006 11:19
Hi,

Good stuff u got that!
Quite helpful
Reply to this.
Doug Karr at 09 Dec, 2006 11:09
GET is restricted by the number of characters allowed to be passed in a URL. I believe that's 1024 for IE.

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.
Reply to this.
Anonymous at 02 Apr, 2007 10:48
rtytry
Reply to this.
Anonymous at 12 Jun, 2007 03:11
the limit is 2083 in IE
Reply to this.
Anonymous at 10 Dec, 2006 03:17
i was looking on how to submit form using post in ajax. your article told me tht. many thnks for tht..
Reply to this.
G.subramanian at 21 Dec, 2006 01:48
Hell sir i don't no the java script but i will training for this tags
Reply to this.
Anonymous at 09 Jan, 2007 02:34
You don't need logs to check the gets and posts. Get the Firebug extension for Firefox and you can see the ajax requests and responses as they happen.
Reply to this.
sandesh at 11 Jan, 2007 11:45
I m looking for something like this only i have started studying Ajax so if anyone knows how to retrieve form created using the aspx page then plz help me?
Reply to this.
Ashok at 06 Feb, 2007 12:20
hi every one,
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
Reply to this.
Draako at 17 Apr, 2007 03:16
You use the php echo statement to create return text, that much I know. what I would like to know is a decent way to verify that the php file received the formdata properly. I have tried using a line of code in my PHP file such as echo $_POST[lorem]; and use the line alert(http.responseText); in my javascript file. Shouldn't I get an alert box saying IPSUM ???

Reply to this.
Anonymous at 11 May, 2009 09:41
just to be on the safe side use $_REQUEST['element_name'] - this covers both POST and GET :-)
Reply to this.
Software Engineering at 17 Feb, 2007 09:58
Thanks for this Good Information... Very Helpful
Reply to this.
Michael Davidson at 20 Feb, 2007 11:06
This is exactly what I needed to get my POSTs working. Worked the on the first attempt. When in doubt google it out.

Thanks,
Reply to this.
Ojasvi at 20 Feb, 2007 12:12
Really a valuable article for the AJAX-POST combination working.
Cheers!!
Reply to this.
Paul at 21 Feb, 2007 09:32
I am working with AJAX. I have been using the GET method and was looking into the POST method primarily for the secure type processing. I have set up the example used in the W3CSchool example for the GET method (very simple). I then altered it to use the POST method shown here (changing the var names, parms passed, and the url destination). When executed on a Windows server the GET method returns the time within 2 secs at the longest. The POST method returns the time in nearly 2 minutes (120 secs). Is there an optimization I am missing? How does one speed this up? The timing is the same whether I check the passed parm in the server-side script.
Thank in advance.
Reply to this.
Paul at 21 Feb, 2007 01:36
I saw a post on Google groups of a similar problem as I has on the speed. The person had a configuration similar to mine (W2K and IE6). That person was wondering if the delay was a known bug or not. All other configeration worked fine for them (W2K and firefox (ff), XP and IE6 and 7, XP and ff, Linux and ff, etc). The code they used in the post is similar to the one presented here except they defined the charset for the content type and used the responseXML instead of the responseText.
Hope this help someone see a potential answer.
Thanks.
Reply to this.
Anonymous at 29 Sep, 2008 05:00
I also faced the problem of slow POST requests with IE on Windows 2000. This forum message at sun.com has a suggestion to "fix" the slow POST request with IE on W2k. I use the following code to limit this workaround exactly to IE on W2k.

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");
}
Reply to this.
Jay at 23 Oct, 2007 12:22
Hi,

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
Reply to this.
Leonardo Todeschini at 21 Feb, 2007 07:29
I don't take this article as something for beginners in AJAX technique, I think this was concepted to teach developers who have done their first steps in AJAX, and stopped at the doubt of "NOW THAT I KNOW HOW TO SIMPLY USE GET .. HOW DO I USE POST?". Well, it was very helpfulll to me and I think that might be very usefull for you if find yourself on the position of that Doubt. Congratulations to the author, a nice and quite simple explanation.

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
Reply to this.
Giles Smith at 22 Feb, 2007 02:28
Can I use this to Post Images or files, and retrieve them using the php $_FILES array?
Reply to this.
Binny V A at 22 Feb, 2007 04:13
Using Ajax to upload files uses a different method - I will write an article about it soon.
Reply to this.
dwikristianto at 02 Apr, 2007 11:11
please, do it.
TIA
Reply to this.
Binny V A at 17 Apr, 2007 11:53
OK - I have written the article about uploading files using Ajax
Reply to this.
Anonymous at 20 Mar, 2007 08:56
Thanks for the article ...
im from indonesia.
Reply to this.
Luis Eduardo at 30 Mar, 2007 05:55
dude.... after a LOT of spent time searching and programming for a way to work with XMLHTTPRequest and POST, you was the UNIQUE that could solve the problem. Thank you very much!
i needed to get the value with the getParameter() of the servlet java API. You found the key ;)
Reply to this.
Sena at 15 Aug, 2008 10:33
Oh... this code also solved my problem with the method post using ajax.

Thanks.
Sena,
Reply to this.
dwikristianto at 02 Apr, 2007 11:09
you just write something i need recently. thanks.
Reply to this.
sohbet at 06 Apr, 2007 03:57
I am installing this plug-in. I think its great. I use google analitics to track my visiters and I have found that 99% of them have javascript so that won't be an issue for me.

Thanks!
Reply to this.
JM at 24 Apr, 2007 01:06
Thanks alot dude i've been looking for this for a while all because IE doesnt support GET method in tha right way like firefox i've tested ur POST method and it wirks just like a wonder and faster
Reply to this.
foro eqfe at 08 May, 2007 12:29
What a strange hallucination! He lives I suppose in the land
prodotti-tipico.blogspot.com/ rel="nofollow">prodotti tipico*
homeward this seems not like reality but like one of the sharp
Reply to this.
JoshT at 20 May, 2007 06:56
Great article, really took alot from it. Unfortunately i'm having some trouble retrieving the data after it's be sent to the destination page, it seems to be cut short. I stepped through the javascript and the params seems to have a length of 5,000+ characters, once i receive call on my aspx page (using asp.net 2.0) it shows the param as only containing less than 1000 characters.

Anyone have a similar problem? any help is greatly appreciated,

Josh T.
Reply to this.
suppie at 24 May, 2007 06:14
gee i was dying to know how to use POST with ajax... everybdy says GET and nothing else.. well this was what i wanted.. :)
Reply to this.
güzelsözler at 30 May, 2007 02:34
Thanks!
Reply to this.
Sam at 31 May, 2007 03:50
Thanks for the beautifull explanation.
Reply to this.
Steph at 04 Jun, 2007 11:17
A brilliant synthesis of PHP/Ajax/Prototype-1.5.1 and more ...
Thank you.
Reply to this.
Its about time at 07 Jun, 2007 10:55
well ive been scouraging the net for answers to my ajax questions for hours.
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...
Reply to this.
Brad at 18 Dec, 2007 04:35
You can use a rand() function and send a useless token in the URL to prevent the server from caching -- that's what w3schools tells you to do at least...
Reply to this.
AwAiS at 10 Jun, 2007 10:19
Thank you very much for explaining the differences between the POST and the GET in AJAX. :]
Reply to this.
Yash at 15 Jun, 2007 09:30
Nice article.It really helps me.

Thank you
Reply to this.
Kumar at 15 Jun, 2007 11:11
Hey thanks,

your post help me a lot.
Reply to this.
bashar at 23 Jun, 2007 05:37
thanks for your post ;)
Reply to this.
Hussain at 06 Jul, 2007 04:20
that was really satisfying & well addressed!
I really dint have to run around here n there for the info!
Thanks!
Reply to this.
WG at 17 Jul, 2007 05:41
This article has been really useful - i have finally got the Post working - I'm having one problem hopefully someone can help with? I want to add a variable into the param. I've added this line after var url,
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?
Reply to this.
WG at 17 Jul, 2007 06:05
i solved it - needed a lesson in strings!
var params = "newtext=" + fmtext;
Reply to this.
fly at 24 Jul, 2007 11:31
i'am from china! 我顶!
Reply to this.
sanjay at 10 Aug, 2007 12:15
hi
I have used ur method as u written but still i m geting proper responce.
can u help me out.
Reply to this.
Shravan at 13 Aug, 2007 10:29
When sending request with POST methosd how could we fetch the sending parameters from server code.
Reply to this.
Anonymous at 26 May, 2008 12:19
in php you can do this:

<?php
foreach ($_POST as $name => $value) {
echo "$name: $value
";
}
?>
Reply to this.
Anonymous at 20 Jun, 2008 03:04
have u got code for this??? Give me plzzzzzz
Reply to this.
myk at 23 Aug, 2007 01:36
Perhaps I missed something....

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...
Reply to this.
Binny V A at 23 Aug, 2007 07:42
It don't have to be revealed - you can take the password from a form field and send it to the server side script.
Reply to this.
myk at 24 Aug, 2007 12:29
so could the params be left blank? or like a '?' placed there
Reply to this.
Binny V A at 24 Aug, 2007 09:51
Just leave it empty.
Reply to this.
myk at 26 Aug, 2007 11:54
THANKS, works like a charm..!
Reply to this.
rapido at 26 Aug, 2007 07:25
thank for you post..its very useful to my new online system...
Reply to this.
Jean Rajotte at 13 Sep, 2007 08:35
just wanna say thanks!
Reply to this.
Gerben van Erkelens at 18 Sep, 2007 06:18
Only one question, Ihave the above scripts in a library.
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.
Reply to this.
Anonymous at 18 Sep, 2007 11:38
good,
and when you use the 'POST' method, and when your param is empty, you shouldn't use send(null), you should use send("") instead.
Reply to this.
Ivan Bernat at 26 Sep, 2007 02:34
Been loking for this for some time now, thanks! :)
Reply to this.
Anonymous at 28 Sep, 2007 12:00
Error: uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.setRequestHeader]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://***********/abcd/seo/include/scripts_java.js :: start_function :: line 202" data: no]
after using this code i m getting above error plz help me
thnks in advance
Reply to this.
Anonymous at 03 Jan, 2008 03:45
to:

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.
Reply to this.
Cinni Patel at 03 Oct, 2007 02:15
Great Article......
I was lookin for the same stuff.... after referring to this article i got my problem solved....
Reply to this.
cookie at 05 Oct, 2007 06:46
I was wondering why POST takes so much longer than the GET? Anyone knows?
Reply to this.
Jay at 24 Oct, 2007 01:33
Cookie, i dont see any difference, they both take the same time for me
Reply to this.
stec77 at 18 Nov, 2007 08:46
It can be a bit tricky to test AJAX workers that take POST parameters. This website helps by allowing requests to be sent by converting GET parameters from a URL into POST parameters: www.gettopost.com/gettopost.html

HTH,
Steve
Reply to this.
Joshua at 30 Nov, 2007 06:11
thanks for the info, it was very helpful.

Regards,
Joshua
Reply to this.
Cristi at 30 Nov, 2007 08:30
I tried also with GET and POST methods to send a params like this text=1+1, but when I'm reading on server the value is 1 1. Do I have to change the Content-Type to something else ?
Reply to this.
Binny V A at 01 Dec, 2007 04:47
To be expected. + will be interpreted as a ' '(space)
Reply to this.
Cristi at 03 Dec, 2007 03:31
there is a solution for this, to read on server + and not ' '(space) ?
Reply to this.
Binny V A at 04 Dec, 2007 01:07
try text=1%2B1
Reply to this.
Paolo at 03 Jan, 2008 04:40
great tutorial, thanks!
Reply to this.
Kal at 19 Dec, 2007 07:44
Great tutorial, had it working in not time.
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/)
Reply to this.
Anonymous at 25 Dec, 2007 05:10
THX
Reply to this.
nidhin at 02 Jan, 2008 10:16
is can i set bountery for content type
Reply to this.
Anonymous at 09 Jan, 2008 11:00
DEAR SIR,

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
Reply to this.
Anonymous at 11 Feb, 2008 11:17
JS "expert" eh? Check out XML DOM. www.w3schools.com/dom/dom_nodetype.asp
Reply to this.
Kamran at 10 Jul, 2008 02:11
lolz JS expert but AJAX newbie - that sounded funny :D
Reply to this.
Matthew Bagley at 15 Jan, 2008 04:58
Hey guys, I read this entry and found it interesting, I have written a function a while ago to handle both POST and GET calls and thought I wuold post it here.


function create_http_handle(TYPE){
var http_handle = false;
if (window.XMLHttpRequest){
http_handle = new XMLHttpRequest();
if (http_handle.overrideMimeType){
if (TYPE == "XML"){
http_handle.overrideMimeType('text/xml');
} else {
http_handle.overrideMimeType('text/html');
}
}
} else if (window.ActiveXObject){
try {
http_handle = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_handle = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_handle){
alert("We are sorry but you are using an outdated browser. To view this site you must update your browser.");
return false;
} else {
return http_handle;
}
}

function sendHTTPrequest(URL, PARAMETERS, ONCHANGE, METHOD, TYPE){
if (TYPE == "")TYPE = "HTML";
http = create_http_handle(TYPE);

http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
eval(ONCHANGE + '();');
}
}

//Kill the Cache problem in IE.
var now = "upid=" + new Date().getTime();
PARAMETERS += (PARAMETERS.indexOf("?")+1) ? "&" : "?";
PARAMETERS += now;

if (METHOD == "POST"){
http.open('POST', URL + PARAMETERS , true);
http.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
http.setRequestHeader("Content-length", PARAMETERS.length);
http.setRequestHeader("Connection", "close");
http.send(PARAMETERS);
} else {
http.open('GET', URL + PARAMETERS, true);
http.send(null);
}
}


Hope it helps someone
Reply to this.
Eugenio at 07 Aug, 2008 12:22
to Matthew Bagley.
I found your comment very usefull to manage both methods easily. Thanks!!
Reply to this.
Eugene at 26 Jan, 2008 10:20
Fine article! Long searched. To the author of many thanks.
Reply to this.
Dave at 05 Feb, 2008 07:20
Nice article, clear, concise and allowed me to convert my Ajax to POST in no time. Cheers!
Reply to this.
Anonymous at 09 Feb, 2008 06:58
yep, don't forget to escape() stuff, you're posting
Reply to this.
Tchotchke at 15 Feb, 2008 10:46
Good article.
Reply to this.
Anonymous at 20 Feb, 2008 07:14
You stated:

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.
Reply to this.
Anonymous at 25 Feb, 2008 08:36
Since we are using post, do we have to urlencode the post parameter data? Or does the request object do this for us?

E.g.

var params = "lorem&" + encodeURIComponent(someLongString);


???
Reply to this.
Anonymous at 25 Feb, 2008 08:38
Does the request object take care of url encoding the post data? Or do we have to do it ourselves?

e.g.

var params = "lorum=" + encodeURIComponent(someLongString);

?
Reply to this.
Anonymous at 28 Feb, 2008 03:02
I am using the "POST" method to send the request.
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.
Reply to this.
abhijit at 04 Mar, 2008 04:07
I have been already using ajax POST before seeing this article. One problem that I am having is sending the "&" character in a string. For example if I want to send "Me & You" as the value of a parameter. Problem is that the string after the "&" is considered as a different parameter. How can I solve this?
Reply to this.
Binny V A at 04 Mar, 2008 04:37
Use encodeURIComponent() function on the string before sending it.

var url = "data.php?people=" + encodeURIComponent(document.getElementById("people").value);
Reply to this.
Anonymous at 04 Mar, 2008 01:02
can any of those methods be used to do a form upload and display image without reloading the page?
Reply to this.
Anonymous at 07 Mar, 2008 05:46
How exactly we do handle any message sent in xmlHttpRequest.send(body).

How do we handle "body" in PHP
Reply to this.
Anonymous at 09 Mar, 2008 10:38
Thanks mate.
Saved my ass.
Reply to this.
Anonymous at 09 Mar, 2008 10:39
Why '\n' character from textaea can't detected, when we send it with GET method via Ajax script ?
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...
Reply to this.
Anonymous at 13 Mar, 2008 10:40
Can anyone please explain if we will send the parameters later, how responseText will return the result as i m getting error of "Object reference not set to ...."
Reply to this.
Anonymous at 14 Aug, 2008 10:54
I had a question, quite a simple one.

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...
Reply to this.
Anonymous at 14 Aug, 2008 10:55
Sorry, I must've accidently pressed 'Reply to this' ... (I'm the writer of the message above)
Reply to this.
Anonymous at 28 Mar, 2008 01:21
thanks so much, the article helped me understand the POST method for xmlhttp... but i still don't understand how is it secured..anyone can do a post to that url with parameters. also can anyone explain me when to use the username and password during

http.open("POST",URL,TRUE,username,password)

thanks in advance.
Reply to this.
Anonymous at 23 Apr, 2008 02:37
Hi, your article helped a lot, so a big THANK YOU!
Reply to this.
Anonymous at 26 Apr, 2008 09:17
thanks for very useful info..,but how can i send these post parameters to a new window
Reply to this.
Anonymous at 27 Apr, 2008 05:42
Amazing, i was really in a fix. but after reading this i found new life, thanks alot
Reply to this.
Anonymous at 08 May, 2008 04:25
Works great in my example page, but in transferring to working effect, I have a few questions :

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?
Reply to this.
Anonymous at 08 May, 2008 11:23
When I run this sample appliation it is asking username and password.
What is the value I havev to give for username and password? Cant we work without username and password?
Thanks in advance.
Reply to this.
Siva at 08 May, 2008 11:24
When I run this sample appliation it is asking username and password.
What is the value I havev to give for username and password? Cant we work without username and password?
Thanks in advance.
Reply to this.
Sephiroth at 12 May, 2008 02:55
The add sign (+) was disappear after ajax post. For example: a+b becomes ab
But if you use http post, its ok.
Reply to this.
Johan at 16 May, 2008 08:48
just a note, you need to put the setRequestHeader before the send command not the open command (which would make more sense to me..
cheers
Reply to this.
santhanavelu at 20 May, 2008 05:03
Thanks a lot. thank u very much
Reply to this.
ruckus at 24 May, 2008 03:28
nice stuff, just i need
Reply to this.
Anonymous at 28 May, 2008 06:31
Nice but post isn't working..
Reply to this.
Anonymous at 28 May, 2008 10:48
Nice helpful ..
Reply to this.
yaniv at 16 Jun, 2008 01:01
Man, i lost so much hair over trying to send utf8 chars via xmlhttp, and it kepts GETting it.
Finally you got me POSTing, I owe you my sanity.
Yaniv
Reply to this.
Anonymous at 16 Jun, 2008 09:33
hi my POST method is sending the parameters but it is not getting received at the Server end. What could be the problem? Any help would be appreciated.
Reply to this.
Jitendra Gupta at 20 Jun, 2008 03:15
How read post params in php
like u are using POST method in AJAX
http.send(body);
Now how u will retrieve this body on server side PHP.
plz help....
Reply to this.
Sviluppo siti web, Italy web developer at 22 Jun, 2008 08:52
This is quite a good article, but i have to add that this doesn't work if you try to ajaxify an external page, for security reasons, it throws an exception!
You can only post a resource on your same web server it seems.

Someone can fix that?
Thank you!
:P
Reply to this.
paris at 07 Jul, 2008 01:17
Very helpful content! Thanks a Lot!
Reply to this.
Anonymous at 15 Jul, 2008 02:55
hem ... the thing is .... can you upload a FILE using XMLHTTP post? ... a pure binary post? i guess you had to struggle with BINARY64 or UNICODE before you get it right. maybe IFRAME technique is a lot more simpler.
Reply to this.
Anonymous at 07 Aug, 2008 06:27
Hello
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
Reply to this.
Anonymous at 18 Apr, 2009 05:56
For security reasons, the function XMLHTTPRequest() cannot open URI's that start with http(s)://. If you want to open such URI you have to use curl or any other server scripting implementation.
Reply to this.
Anonymous at 12 Aug, 2008 06:47
Just wanted to say thanks. Good article. Helped me out quite a bit.
Reply to this.
Anonymous at 14 Aug, 2008 10:55
I had a question, quite a simple one.

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...
Reply to this.
Anonymous at 14 Aug, 2008 11:08
Nevermind ... It was a typo:

ajaxObj.onreadystatechange = 'ajaxStdCb';

Instead of

ajaxObj.onreadystatechange = ajaxStdCb;

So my callback was a string and couldn't be converted :P
Reply to this.
CutePro at 18 Aug, 2008 04:11
Good explanation for Ajax using GEt and post. thank you man.
Reply to this.
Katy at 29 Aug, 2008 11:31
Thanks a lot for this - I couldn't figure out why I still was getting the form stuff via the querystring, not the form and I'd missed "("Content-length", params.length);"

Thanks a lot for your help :)
Reply to this.
Anonymous at 10 Sep, 2008 07:43
I used post method in notes subform and call a notesagent(as below)
-----------------------
// 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?
Reply to this.
Anonymous at 19 Sep, 2008 01:38
Hi to all ,

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
Reply to this.
Anonymous at 26 Sep, 2008 04:58
I am writing a generic ajax function and your article was great for me.
Thanks a lot for your article.

Jurandi
Reply to this.
Anonymous at 06 Oct, 2008 04:05
I want to submit a form from .Net to PHP and take response and use that response in .Net. If the URL of PHP site or page is by URL then no problem but if It submitted by post method then how to pass the variable by post method from .Net to PHP page.
Reply to this.
Anonymous at 26 Oct, 2008 02:37
Solved problem of slow POST requests with IE6 on Windows 2000:

correct : http.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
incorrect: http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Reply to this.
Daniel Crane (Dandymon) at 27 Oct, 2008 03:51
Superb!
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
Reply to this.
Steven at 06 Nov, 2008 12:20
POST problem in FIREFOX 3.0.3 select value doesn't post when submit is clicked but works in IE 7.0
<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?
Reply to this.
Binny V A at 06 Nov, 2008 07:56
Remove the 'javascript:' from 'onFocus="javascript:callOptionList(this,'el1',1);"'
That might fix it.
Reply to this.
Steven at 06 Nov, 2008 10:29
That is the function that makes the ajax call.
Reply to this.
Steven at 06 Nov, 2008 10:47
'onFocus="callOptionList(this,'el1',1);"' this doesn't work either.
Reply to this.
HP at 24 Nov, 2008 12:22
Steven, I am having the same issue with Firefox 3.0.3 and POST. Did you find a fix for it?
Thanks
Reply to this.
Anonymous at 21 Nov, 2008 11:54
Great stuff. Ummm, but using POST does not mean i will get free of passing parameters? What's the point to call it Ajax using POST method if either way it uses parameters... i was looking something more like a function that uses Ajax that uses the POST information of a simple form...
Reply to this.
AJAX Post Request at 05 Dec, 2008 04:56
Nice tutorial about AJAX POST method request.
Thanks.
Reply to this.
doremon at 23 Dec, 2008 12:53
Help me, i have two combobox. On firefox3, when frist combo change value , the second combo will change value.It's ok. But when i submit my form, i can only get value of frist combo the second can't( don't have in array POST ). If i do the same by IE , it's OK.( i use method post and get for ajax )
Reply to this.
Hihi at 07 Jan, 2009 12:45
Hi!

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.
Reply to this.
Hihi at 07 Jan, 2009 11:10
I've solved my problem!
Reply to this.
Anonymous at 18 Jan, 2009 11:22

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.

Reply to this.
Anonymous at 27 Feb, 2009 01:38
I have a unique issue, I am trying to send form values through ajax, but very rarely the param doesn't get passed to the server. Below is the javascript code.

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);
Reply to this.
Anonymous at 07 Apr, 2009 05:38
Simple. easy to understand and just GREAT article!
Reply to this.
Anonymous at 25 Apr, 2009 11:38
Thanks!

if you want to see all $_POST, use
<?php
print_r($_POST);
?>
You may also see $_GET or $_REQUEST etc
Reply to this.
santhosh at 02 May, 2009 12:12
We are calling any web script file through open function,it will have three arguments.What is the
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 ...
Reply to this.
Joris at 17 May, 2009 05:36
If you expect UTF-8 strings, you need to have some extra logic to determine the content-length:


http.setRequestHeader("Content-length", binaryLength_UTF8(params));

function binaryLength_UTF8(str)
{
var bytes, charCode, a, len;

bytes = 0;
for (a = 0, len = str.length; a < len; a++)
{
charCode = str.charCodeAt(a);
if (charCode < 128) //2^7
bytes += 1;
else if (charCode < 2048) // 2^11
bytes += 2;
else if (charCode < 65536) // 2^16
bytes += 3;
else
bytes += 4;
}

return bytes;
}
Reply to this.
Anonymous at 19 May, 2009 05:37
I had to use this to process a form that generated a URL > 2048 chars because of IE's URL length restriction. This was a very helpful tutorial. Thank you.
Reply to this.
Anonymous at 01 Jun, 2009 11:43
I tried with the code for sending data to a page through POST method. I am receiving Access Denied exception. What might be the reason?
Reply to this.
Anonymous at 02 Jun, 2009 10:54
my POST failed on ie7/IIS backend, but works on chrome & firefox 2 + 3. The site uses windows authentication and to get it to even get to the page on IE7 & firefox2, have to make the file annon access* (works for chrome, firefox3 without though).

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.
Anonymous at 17 Jun, 2009 04:18
my POST failed on ie7/IIS backend, but works on chrome & firefox 2 + 3. The site uses windows authentication and to get it to even get to the page on IE7 & firefox2, have to make the file annon access* (works for chrome, firefox3 without though).

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.
Reply to this.
Tim Higham at 20 Jun, 2009 03:43
Having problems using onreadystatechange within a JS class - call to a function outside of this class is possible, however defeats the point of encapsulation.
How can I do this??
Reply to this.
Tim Higham at 20 Jun, 2009 03:54
Have sort of solved this - is there an easier way though.
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);
}
}
Reply to this.
Anonymous at 29 Jun, 2009 01:26
erer
Reply to this.
Halı Saha at 29 Jun, 2009 02:06
I was looking for this kind of applications with ajax.This is a very useful post that responds all my needs. Thanks
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.