Exchange standard POST form

Asked

Viewed 135 times

0

I have a Jquery function that creates a JSON object exactly as I need it. At the end of this function I send a POST to an API by passing this object

$.post('http://localhost:3000/testStatus', objeto)

I call the function that creates this object in a butao inside the form, something like:

<form method="post" action="/testStatus">
   <!-- Resto do html, contento inputs e tudo mais... -->
    <button onclick="postData()">INICIAR</button>
</form>

It happens that the function sends the POST as I want and form also sends another POST, IE, in one click the form sends 2 POST in a row. I can’t replace the method="POST" by GET or remove it. I need to send only the POST of my function postData()

An alternative to this would be to switch pages ( go to testStatus ) through my jquery post, so I wouldn’t need to put the button inside the form. But I can’t do it with jquery

  • Place $("form").submit(function(e){ e.preventDefault(); }); in the script to prevent the form from being submitted.

  • This works in part, but I still need to load the testStatus page. And it is only loaded through a post

  • So why don’t you do the post by action instead of jQuery. I’m not getting what you want to do right :/

  • I happen to be generating several inputs automatically through Handlebars, and it turns out that it is generating these inputs without the name, then I can’t capture them. Earlier I tried to make a function using jquery to put the name attribute in these inputs, but it turned out that it didn’t work.. then I opted for this solution, but it’s not as I wanted..

  • The testStatus page only loads via post? You want to do Ajax and then load the page?

  • Yes, it only loads via POST. In this case, it would be before.. I made a function that when you click the button, it creates an object that would be passed to the page testStatus and she should carry the page along with this object

Show 2 more comments

1 answer

2


Place an Hidden input in the form and send the object to it before the normal Submit via the action post, and not via Ajax. So you can receive this input in the backend and treat the object as you want.

It would be something like that:

<form...>
   ....
   <input type="hidden" name="objeto">
   <button>INICIAR</button>
</form>

<script>
$("form").on("submit", function(e){
   e.preventDefault(); // cancela o submit automático
   var $this = $(this);

   // código que cria o objeto

   // insere o objeto no campo
   $("[name=objeto]").val(objeto);

   // delay para inserir dados no input antes do submit
   setTimeout(function(){
      $this.submit(); // envia o form
   }, 100);
});
</script>

Browser other questions tagged

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