How to pass form data using POST method and JS submit() ?
I would like not to use AJAX.
I can achieve that by using JS and GET method, but my goal now is to use JS (probably with submit() ) and POST method.
Please give a simple working example.
Thank you!
Edited: Sorry, I will be more specific. Here is a simple code I have:
<form name=\"myform\" action=\"\">
Search: <input type='text' name='query' />
<a href=\"javascript: submitform()\">Search</a>
</form>
<script type=\"text/javascript\">
function submitform() { document.myform.submit(); }
</script>
When I insert "word" into the input field and press Search, the URL becomes "../index.php?query=word" and that means that form data is passed like GET method.
And my goal is to remove any form data from URL and pass it like with POST method.
Edited: ohh.. I just added method=post and no form data in the URL anymore :)
Just have a form and submit it.
form = document.forms[0] //assuming only form.
form.submit();
Specify a method
attribute on your form.
<form name="myform" action="" method="POST">
It will cause the form to be submitted as a POST.
As mentioned already, you can use a form. I find it useful to have a function which creates a form on-the-fly and submits it - that way you don't need to clutter your markup with forms until they're needed by your JS.
function PostObjectToUri(uri, obj) {
"use strict";
var json, form, input;
json = JSON.stringify(obj);
form = document.createElement("form");
form.method = "post";
form.action = uri;
input = document.createElement("input");
input.setAttribute("name", "json");
input.setAttribute("value", json);
form.appendChild(input);
document.body.appendChild(form);
form.submit();
};
Obviously that example JSON-serializes an object into a string and sets it on a single input, but you could adapt it to do whatever you need.
EDIT: I'm not actually sure whether you even need to append to the DOM before submitting - can anyone clarify?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With