Home > Back-end >  How to submit a form using javascript with GET, when the form's method is POST?
How to submit a form using javascript with GET, when the form's method is POST?

Time:11-19

Context

I have a working standard form, with method POST, with a standard submit button, and I would like to leave this in this way.

<form id="myform" method="post"...  >
   ...
   <input type="submit  .../>
</form>

However in some circumstances, I would like to programmatically send the form data to server side and re-render the form. Sending the form data with GET would be great this case.

Question

How can I achieve that document.myform.submit(); use the GET method, instead the POST what is declared in the <form ...> element?

CodePudding user response:

In my opinion, I will do this(Explicitly Submit form from js)...

<form id="my-form" method="post"...  >
   ...
   <button id="btn-submit" type="button"  .../>
</form>

<script>
 const submit = document.getElementById('btn-submit');
 submit.addEventListener('click', function(event) {
 event.preventDefault();
 const form = document.getElementById('my-form');
 if(SOME CONDITION) // some usecases in which we need different method.
 {
   form.method = 'POST';
 } else {
   form.method = 'GET';
 }
 form.submit();
});

</script>

CodePudding user response:

You can always send your data to your serverside by AJAX request and do whatever you please by the response value that you receive. There are plenty of examples if you research it. Also here's another source to help you get through this problem. Click here

  • Related