POST data with JavaScript

Posted by Andrea on 2009-07-07 12:07
The HTML 4.0 specs
  • If the method is "get" - -, the user agent takes the value of action, appends a ? to it, then appends the form data set, encoded using the application/x-www-form-urlencoded content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
  • If the method is "post" --, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype attribute.

What are the benefits of performing POSTs via JavaScript?
  • Perform redirects programmatically
  • Post data without annoying the user
  • Avoid the misuse of query string and beautify URLs

The 'post' function
Copy and paste the following code in the HEAD section of your HTML page
<script language="javascript">
  function post(dictionary, url, method) {
    method = method || "post"; // post (set to default) or get

    // Create the form object
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", url);

    // For each key-value pair
    for (key in dictionary) {
      //alert('key: ' + key + ', value:' + dictionary[key]); // debug
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden"); // 'hidden' is the less annoying html data control
      hiddenField.setAttribute("name", key);
      hiddenField.setAttribute("value", dictionary[key]);
      form.appendChild(hiddenField); // append the newly created control to the form
    }

  document.body.appendChild(form); // inject the form object into the body section
  form.submit();
  }
</script>

How do I use it?
Copy the following code in the BODY section of your HTML page.
As you can see a dictionary object is declared as first, then two parameters are added.
You can add as many parameters as you need.
<script language="javascript">
  var myDictionary = [];
  myDictionary["1stKey"] = "1stValue";
  myDictionary["2ndKey"] = "2ndValue";
</script>

<input type="button" value="Click me to POST" onclick="javascript:post(myDictionary, 'destination.html');" />
<input type="button" value="Click me to GET" onclick="javascript:post(myDictionary, 'destination.html', 'get');" />

The post function accepts a dictionary object, a destination URL, and optionally, the method (post or get, case in-sensitive).

Comments

Andrea commented
Gravatar
Just used this script to POST data across VisualForce pages (Salesforce.com), works fine.