2008.01.07

Javascript JSON page post

Kategori: JSON, Programmering — Michael Schøler, Kl. 16:19:32

Today I had a need to make a POST request which submits a JSON object to a processing page. Normally I would go about embedding a form in the page and invoking it’s submit programatically, using a GET request with simple querystring parameters, or I would have used the Prototype Ajax.Request method. But GET requests are limited to submitting 255 bytes (albeit higher limits are implemented in various browsers), which was insufficient for the task at hand and would therefore only lead to Error code 414 (Request-URI Too Long), and I needed a complete page repload and the page URL to change in the browser.

I came up with this simple form-injection solution (no rocket science included):

JsonPagePost.js

  1. var JsonPagePost = {
  2.   post: function(sPostUrl, sParamName, oJson) {
  3.     var oForm = document.createElement(“form”);
  4.     oForm.method = “post”;
  5.     oForm.action = sPostUrl;
  6.     var oField = document.createElement(“input”);
  7.     oField.type = “hidden”;
  8.     oField.name = sParamName;
  9.     if (typeof oJson === “object”) {
  10.       oField.value = Object.toJSON(oJson);
  11.     }
  12.     else {
  13.       oField.value = oJson;
  14.     }
  15.     oForm.appendChild(oField);
  16.     document.appendChild(oForm);
  17.     oForm.submit();
  18.   }
  19. };

With this you can setup eg. a button like this (requires prototype.js):

TestJsonPagePost.html

  1.   <script language=“javascript” src=“prototype.js” type=“text/javascript”></script>
  2.   <script language=“javascript” src=“JsonPagePost.js” type=“text/javascript”></script>
  3.   <title>Post JSON test</title>
  4. </head>
  5.   <input type=“button”
  6.     onclick=“JsonPagePost.post(’TestJsonPagePost.html’,'jsonParam’,{test:42})” />
  7. </body>
  8. </html>