Using Javascript to POST data between pages
Posted by pcfinch on June 2, 2008
The following is a simple example of how to submit data from one HTML page to another using the POST method from Javascript. Normally, if data needs to be sent from one HTML page to another, it is done by appending the information to the query parameter of the the URL in the familiar “name=value” format. e.g.
< href="post.aspx?user=peter&cc=aus">Click</a>
Although this works fine, in most cases, problems occur when there is a lot of data to send and the URL exceeds about 2000 characters. The other disadvantage is that the URL looks ugly. The traditional method to get around this is to POST the data using a form. e.g.
<form name="myform" method="post" action="post.aspx"> <input name="user" value="peter"/> <input value="cc" value="aus"/> <a href="javascript:myform.submit()">Click</a> <form>
This works fine, however, it does tend to make the formatting of the resulting HTML difficult and increases the size of the final HTML page significantly if there are lots of links on it.
The following javascript function takes the URL of the target page and an associative array of name/values paires and POSTs the data to the supplied URL by dynamically creating a form and then submitting it.
function postwith (to,p) { var myForm = document.createElement("form"); myForm.method="post" ; myForm.action = to ; for (var k in p) { var myInput = document.createElement("input") ; myInput.setAttribute("name", k) ; myInput.setAttribute("value", p[k]); myForm.appendChild(myInput) ; } document.body.appendChild(myForm) ; myForm.submit() ; document.body.removeChild(myForm) ; }
To insert a link into a page just use a normal anchor tag in the HTML and call the function.
<a href="javascript:postwith('post.aspx',{user:'peter',cc:'aus'})">click</a>
This works on Microsoft IE, Mozilla Firefox and OS X Safari.
Matthew said
Hello, thanks for the code. This is something that will be very useful. I’ve used your code on a site I am working on, and indicated where I got it from, etc. in a js comment.
awat said
Thank so much.
Mike said
Thanks. This is very usefull 😀
Sejo said
Great! Thanks!
Steve said
OMG, this saves my ass! Great function. VERY clean code. Congrats, and thanks to google for letting it be discoverable (search string )!
acalvet said
Very, very nice! Thanks!
Kerosen said
Excelent function, keep posting good stuff
Boray Eris said
Thank you sir. It really helped me.
Denis said
Thanks for your useful script!
Arthur said
AWESOME! thank you so much!
Pankaj Agrawal said
Lovely Code,Thanks…
Fadi KHOURY said
Very strong piece of code Cheers!
Andy Koppel said
Keep up the good work! This code snippet eliminated a hell lot work from me as a php developer.
Niki said
Hi!
Is it possible to read POST data via Javascript? I know it is possible using querystring via GET method between HTML pages.
Can someone let me know or the admin? I am trying to POST data between HTML pages and second/final page reads it via Javascript.
Pls lemme know.
tandon1.nikita[]at[]blogger.com
pcfinch said
Hi Niki,
Just to clarify (you probably know this anyway) but data does not get posted to a webpage. A “post” is used to send data from the browser to the server, not from page to page or from the server to the page. Even if it appears to be going from one page to another, it is actually going from the browser, to the server and then back to the browser.
If you want to read the data posted sent to a page from Javascript, then you would need to get the server to write the posted data (sent from the browser to the server) into the webpage somewhere before it sends the page back to the browser. This could be done using a hidden Form field (like ASP.NET does), or as just text in the document. You can then use the javascript (at the browser) to read the Form objects on the page or the DOM to read the text.
However, if you are talking about “inter-page communication”… i.e. you have two web pages open and you want to send data between it, then it might be possible, but I don’t know how.
I hope this helps.
unknown said
if you don’t like to send informations over the GET parameters and you’ll need a real client solution to transfer data between 2 pages then use cookies to transfer the data.
James said
Thank you! I incorporated your function into my own open source project (with a reference to the URL of this blog entry.) Unlike PHP, Javascript isn’t exactly my forte, so this helped me out a lot!
Dave McInnes said
Managed to get it working with a button aswell:
thanks so much, i’ve been struggling with this for ages
Mike said
If I wanted to have another three or four inputs for the post, how would that look?
searchyBy=Database
searchType=Basic
term= (would prefer users to enter this in a text box).
Thank you.
Mike said
This seems to work to have a variable value for term:
form name is javapass
text field is called term
term:[document.javapass.term.value]
I also just added other values into the javascript string since they I guess are all read into the array in the function?
Wish I found your site sooner. This saved me a lot of frustration.
Thanks.
Jeyakumaar said
This is really so cool… Works like as I expected… Thanks mate!!
Ravi said
Pease of diamond!!!!!
Ravi said
Its a piece of diamond
Maximiliano said
Excellent post! Tanks!
Peter said
This is great, but I need one other thing. I want the script that I post to to pip up in a new window. Currently I do this with an onclick=”window.open(…)” on the input/submit element but how do I use this and still have the data POSTed? Can it be done with the onsubmit on the form element?
Joe said
Wow! Nice work. I was able to use this with little modification. Thank you!
Mark said
Thanks for this, it helped me on an AS3 cross domain scripting problem!
Mulenga said
Very usefull! Thx a lot!
Tehmina said
How i can post data on the other page through JavaScript.?
Jurgen said
Found it two years after you’ve posted it and still this is the best way I’ve found so far.
Really helped me a lot with this.
Rain Lee said
Nice code, i modded few to make it work on my website. Cool!
Paul said
My friend this piece of code….even though I found it two plus years after you posted…..I am very impressed and thankful……I have been search for a way to do something like this for days…….
Thank you.
a user said
thank you very very much!
Djekkoo said
Thanks man!
U just saved some hours of research!
Mehmet Uluturk said
It’s very simple and useful code. Thanks.
Aubrey said
Shit yeah! Thanks for this
Ryan Williams said
Thanks for this solution. I needed this.
Peter said
Did anyone ever get a solution to the requirement to have the posted URI open in a new window?
apepsy said
function postwith (to,p) {
var myForm = document.createElement(“form”);
myForm.method=”post” ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement(“input”) ;
myInput.setAttribute(“name”, k) ;
myInput.setAttribute(“value”, p[k]);
myForm.appendChild(myInput) ;
}
myForm.target = “_blank”; // same href target=”_blank”
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
apepsy said
// post new window
function postwith (to,p) {
window.open(“”, “newwin”, “width=300, height=210”);
var myForm = document.createElement(“form”);
myForm.method=”post” ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement(“input”) ;
myInput.setAttribute(“name”, k) ;
myInput.setAttribute(“value”, p[k]);
myForm.appendChild(myInput) ;
}
myForm.target = “newwin”;
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
Guillermo said
Hi, Peter.
Just add:
myForm.setAttribute(“target”, ‘_blank’);
to open a new window with the posted data.
pcfinch said
Cool! Thanks 🙂
herrywon said
thanks … i’m finding it. So thank !!!
Benjamin said
Thank you!
charly said
After hours trying to post to a download php, yours is the solution that worked!!! I need to send the query string, a couple of arrays with field names, etc and couldn’t figure it out with ajax/jquery (the download php would send back all the stuff to the calling program) and a form was overkill. But yours is delightful. Javascript is more beautiful everyday to me!
Stan VanDRuff said
Elegant, simple, and tight. One of the most useful posts I’ve read anywhere. Thanks!
Stefan said
Thank you for this, however, I get this error in Firefox (but not in IE):
“myForm.submit() is not a function.”
I read via Google that normally this is an error you get when one of the form inputs is named “submit” – which isn’t true in this case?
It works in IE except that before the next page loads, two input boxes appear on the page. Is there a way to hide these boxes from appearing?
Stefan said
The easiest way I found to prevent the boxes from appearing, is to add the following statement to the javascript code above:
myInput.setAttribute(“type”, “hidden”);
pcfinch said
Good suggestion… Thanks!
Stefan said
There is no problem with your code.
I found my problem. Turns out I used the following code:
var myForm = document.createElement(“form_redir”);
Since there is no valid HTML tag called “form_redir”, the submit() function could not be found.
Thanks to the folks at StackOverflow for pointing this out to me.
foldertrack said
Thanks pcfinch.
This is exact.
Appreciate it.
Enes said
Used it for one of my project, and i can definately say that it saved my ass. Thanks for sharing dude
J Jeyaseelan said
Very nice code sample indeed. kudos
yance128Yancw said
That is realy cool script… my submitting problem have been solved with it !!! Cheers for you 🙂
Juan said
THANKS a LOT after the years your post is the best I found (many hours googling and nothing)
John said
Great post. Saved me a ton of time on a legacy jQuery solution I’ve been left to support. (where I needed to have a page simulate a post after an async event). Much appreciation for sharing.
Blake's Application Development Blog – Using JavaScript to simulate a form post said
[…] https://mentaljetsam.wordpress.com/2008/06/02/using-javascript-to-post-data-between-pages/#comment-12… […]
Avinash said
Hello Sir,After Posting the value , How to retrieve the value on next page?
pcfinch said
The values are posted to the server (no the page), so your web application (sever side) would have to retrieve the values from the request (depends on what you are using c#, php, etc on the exact details of this) and reuse them on the “next page” or include them in the response HTML.
patibandha said
need help..
i try to add this script in my page.. this script is working fine in Chrome.. but it is not working in IE and Firefox
any idea..
shogishack said
Simple and elegant. I am glad I googled before wrestling with jquery
Sky said
That’s very useful, but screwed up your SEO
Daniel Denayer said
Excellent piece of clockwork !
I could put it in use to save a somewhat complex application that was hitting a wall due to GET’s data-volume limitations.
Thanks for having shared (4 years ago !) this smart design with the community.
shontzomania said
Great to see this still going! My only suggestion would be to add an if clause at the very start inside the for loop to check p.hasOwnproperty(k) just so you don’t get any extra values from the prototype using an unfiltered for…in loop. So it would look like if(p.hasOwnProperty(k)){do work…}
Arthur said
Saved my life!
steve said
Man i really appriciate your help. This has helped me a lot.
Kees said
Excellent post.
Still it took me a while to get it working as i needed to adjust it.
I packed it into a function to have it add stuff dynamicly depending on the situation. Also i added the hidden flag to keep it from being seen. This is what i ended up with.
{
var myForm = document.createElement (“form”);
myForm.method = “post”;
myForm.action = “http://’
+
ev_URL_MainSite
+
‘/mailme.php”;
myForm.target = “sc_ms_response”;
function jvs_sc_sm_ah_AddEntry (
Name,
Value
)
{
var myInput = document.createElement (“input”) ;
myInput.setAttribute (“type”,”hidden”);
myInput.setAttribute (“name”,Name);
myInput.setAttribute (“value”,Value);
myForm.appendChild (myInput);
};
jvs_sc_sm_ah_AddEntry (
‘its name’
‘its value’
);
document.body.appendChild (myForm);
myForm.submit ();
document.body.removeChild (myForm);
}
You can add any amount of entries by subsequent calls of _sc_sm_ah_AddEntry. Good Luck and again thanks for the post.
Kees said
Please replace the following
myForm.action = “http://’
+
ev_URL_MainSite
+
‘/mailme.php”;
with the following
myForm.action = “http://”
+
ev_URL_MainSite
+
“/mailme.php”;
The single quotes are replaced by double quotes.
thx, Kees
Puneet said
Thanks a lot…….
vitamin said
Aw, this was a very good post. Taking a few minutes and actual effort to generate a top notch article… but what can I say… I hesitate a whole lot and never manage to get nearly anything done.
robercik101-95 said
I have problem with it, beacuse when I use postwith, in Bug Console in FireFox there is error – “document.body is null”
What I do wrong?
There is code:
function postwith (to,p) {
var myForm = document.createElement(“form”);
myForm.method=”post” ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement(“input”) ;
myInput.setAttribute(“name”, k) ;
myInput.setAttribute(“value”, p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
postwith(‘http://somesite.com/save.php’,{txt:’HELLO WORLD!’})