Wednesday, December 9, 2009

Dynamically add POST form in PHP and javascript

Sometimes you want to send data as POST to a page based on a button clicked. A possibility is to generate this form on the fly using javascript:


<html>
<body>
<script type="text/javascript">
//Create form to send values as post to the update status page.
var form = document.createElement("form");

form.setAttribute("method", "post");
form.setAttribute("action", "computationpage.php");

var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "inputValue1");
hiddenField.setAttribute("value", 999);
form.appendChild(hiddenField);

var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "inputValue2");
hiddenField.setAttribute("value", "this is a string");
form.appendChild(hiddenField);

//Create hidden div to contain the form.
var div = document.createElement("div");
div.setAttribute("style", "visibility:hidden");
div.appendChild(form);
document.body.appendChild(div);

form.submit()
</script>
</body>
</html>


This code would when call, create a form, add it to a hidden div at the bottom of the page and submit the form.

EDIT: added HTML, BODY, and SCRIPT tags. This is all that should be needed for this script to work standalone (its not valid XHTML 1.0 Strict though :)).

3 comments:

  1. Hi
    Iam trying this code but I am getting some errors:

    1) document.body.appendChild(div);
    is not recognized like a valid expression???
    2) form.submit();
    generates an http 500 error???

    could some one help me?
    thanks
    Mic

    ReplyDelete
  2. Hi
    These errors seem strange to me. :) This exact form works fine for me, try commenting out the 'div.setAttribute("style", "visibility:hidden");' and 'form.submit()' lines and see if you get a form on your page.

    For the 1. error, could it be conflicting with other functions or frameworks? I combine it with jQuery which uses append instead of appendChild, but that is only used on jQuery objects... Dunno.

    For the 2. error, this sounds like there is an error in the page you are trying to send the form to. Either that it isnt there, that you are forbidden to see it or that it cant handle the post data that you are sending to it. Try creating a form in regular HTML and post to it and see if it still works.

    I will add the minimal HTML tags that I needed to make this work by itself.

    Good luck. :)

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete