How to make a JavaScript POST to a page

Scenario:

You want to post data from one page to another with JavaScript.

Solution:

First, create a JavaScript function in your page.  This will need to be surrounded by script tags and should probably live in the head tags (or have a js file included there):

JavaScript

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) ;
}

Now, you can post via click (or other events) on elements. This example I’ll just use a hyperlink:

<a href="javascript:postwith('post.php',{firstname:'john',lastname:'smith'})">click</a>