Mental Jetsam

By Peter Finch

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.

About these ads

68 Responses to “Using Javascript to POST data between pages”

  1. 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.

  2. awat said

    Thank so much.

  3. Mike said

    Thanks. This is very usefull :D

  4. Sejo said

    Great! Thanks!

  5. Steve said

    OMG, this saves my ass! Great function. VERY clean code. Congrats, and thanks to google for letting it be discoverable (search string )!

  6. acalvet said

    Very, very nice! Thanks!

  7. Kerosen said

    Excelent function, keep posting good stuff

  8. Boray Eris said

    Thank you sir. It really helped me.

  9. Denis said

    Thanks for your useful script!

  10. Arthur said

    AWESOME! thank you so much!

  11. Pankaj Agrawal said

    Lovely Code,Thanks…

  12. Fadi KHOURY said

    Very strong piece of code Cheers!

  13. Andy Koppel said

    Keep up the good work! This code snippet eliminated a hell lot work from me as a php developer.

  14. 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.

  15. 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!

  16. Dave McInnes said

    Managed to get it working with a button aswell:

    thanks so much, i’ve been struggling with this for ages

  17. 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.

  18. Jeyakumaar said

    This is really so cool… Works like as I expected… Thanks mate!!

  19. Ravi said

    Pease of diamond!!!!!

  20. Ravi said

    Its a piece of diamond

  21. Maximiliano said

    Excellent post! Tanks!

  22. 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?

  23. Joe said

    Wow! Nice work. I was able to use this with little modification. Thank you!

  24. Mark said

    Thanks for this, it helped me on an AS3 cross domain scripting problem!

  25. Mulenga said

    Very usefull! Thx a lot!

  26. Tehmina said

    How i can post data on the other page through JavaScript.?

  27. 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.

  28. Rain Lee said

    Nice code, i modded few to make it work on my website. Cool!

  29. 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.

  30. a user said

    thank you very very much!

  31. Djekkoo said

    Thanks man!
    U just saved some hours of research!

  32. Mehmet Uluturk said

    It’s very simple and useful code. Thanks.

  33. Aubrey said

    Shit yeah! Thanks for this

  34. Ryan Williams said

    Thanks for this solution. I needed this.

  35. 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.

  36. herrywon said

    thanks … i’m finding it. So thank !!!

  37. Benjamin said

    Thank you!

  38. 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!

  39. Stan VanDRuff said

    Elegant, simple, and tight. One of the most useful posts I’ve read anywhere. Thanks!

  40. 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”);

    • 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.

  41. Thanks pcfinch.

    This is exact.

    Appreciate it.

  42. Enes said

    Used it for one of my project, and i can definately say that it saved my ass. Thanks for sharing dude

  43. J Jeyaseelan said

    Very nice code sample indeed. kudos

  44. That is realy cool script… my submitting problem have been solved with it !!! Cheers for you :)

  45. Juan said

    THANKS a LOT after the years your post is the best I found (many hours googling and nothing)

  46. 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.

  47. [...] http://mentaljetsam.wordpress.com/2008/06/02/using-javascript-to-post-data-between-pages/#comment-12… [...]

  48. 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.

  49. 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..

  50. shogishack said

    Simple and elegant. I am glad I googled before wrestling with jquery

  51. Sky said

    That’s very useful, but screwed up your SEO

  52. 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.

  53. 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…}

  54. Arthur said

    Saved my life!

  55. steve said

    Man i really appriciate your help. This has helped me a lot.

  56. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: