How to make a form submission without form?

Asked

Viewed 433 times

2

The question may seem strange. But on a certain page I would like to make a submit, as a form, when clicking a button, but without the form presence in HTML.

Is there any way to simulate the submission of a form without it existing on the page?

Example:

<!-- Faz um paranauê para submeter a página via post sem formulário -->
<button id="submit"></button>

Observing: I don’t need to fill out a form or anything. I just need that when you click the button, a form submission is sent (POST method). And this is not an ajax request.

2 answers

6


Being only the need to submit the form, you could use ajax, but it does not seem to me the case, yet there is a new Html5 attribute that can help you, is the form="..." and create a hidden form (so you won’t need javascript):

<!--// formulário oculto -->
<form action="rota" method="POST" id="meuformulario">
  <input type="hidden" name="chave1" value="1">
  <input type="hidden" name="chave2" value="2">
  <input type="hidden" name="chave3" value="3">
</form>

...

<p>....</p>


...    

<button type="submit" form="meuformulario" value="Chamar">Chamar (trigger)</button>

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

In addition it is still possible to control the form with other attributes by <button>:

  • formaction exchange form action pointed by attribute form=""

  • formenctype this attribute changes the ecntype form pointed by the attribute form="", values that can be used:

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  • formmethod exchange the method of <form> pointed by the attribute form=""

  • formnovalidate exchange the value of <form novalidate=""> pointed by the attribute form="" is a Boleano value.

  • formtarget exchange the target of the window instance you want the request to be made, examples of values accepted:

    • _self
    • _blank
    • _parent
    • _top

Example:

<button formaction="/pagina" formenctype="multipart/form-data" formmethod="POST" formtarget="_blank">

2

Yes, there is a way. You can do the same way you use to submit a form via javascript, but you will only use what is created by document.createElement

Thus:

var fake_form = document.createElement('form');

fake_form.method = 'POST';

document.querySelector('#submit').addEventListener('click', function()
{
     fake_form.submit();
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.