Two actions in the same form

Asked

Viewed 3,954 times

1

Hello! I need to have two actions in the same form. I researched some solutions and did as follows:

<form id="formnewsletter" name="formnewsletter" method="POST">

   <input type="text" name="nome" id="nome" />
   <input type="text" name="email" id="email" />

   <button type="button" onClick="enviaForm();">Enviar</button>

<script>
function enviaForm(){
    document.getElementById('formnewsletter').action = 'form_newsletter.php';
    document.getElementById('formnewsletter').submit();

    document.getElementById('formnewsletter').action = 'https://www.rdstation.com.br/api/1.2/conversions';
    document.getElementById('formnewsletter').submit();
}
</script>

</form>

The problem is that it only triggers the second action, if I reverse the position of the actions, then the other one is not working. How could I fix this? With Ajax would be better?

Thanks in advance!

2 answers

2


I managed to send the form to two actions. If anyone needs it, follow the code below:

    <script type="text/javascript">
        function enviaForm(nome,email){
            $.ajax(
                    {
                      type: "POST",
                      url: "form_newsletter.php",
                      data: "&nome="+nome+"&email="+email,
                      beforeSend: function() {
                      },
                      success: function(txt) {
                        if(txt.status=='success')
                            alert("E-mail cadastrado com sucesso!\n\nObrigado!");
                        else
                            alert("E-mail não cadastrado.");

                            EnviaForm2();
                      },
                      error: function(txt) {
                      }
                    }
                );

        }


        function EnviaForm2()
        {
            document.getElementById('formnewsletter').action = 'https://www.rdstation.com.br/api/1.2/conversions';
            document.getElementById('formnewsletter').submit();
        }
    </script>

2

Your code will do the POST for only one of the two Urls, and then it will be redirected to the page the form was sent to. See this example.

When you use .submit() in js the browser will make the POST request and redirect to the page where the form was sent, as if the user had normally clicked on the form Submit.

In your case the best thing to do is to make the requests with Ajax and then show a message to the user saying that he was subscribed to the two newsletters. In jQuery you can use ajaxComplete.

  • Friend I appreciate your help but I do not have a good knowledge with ajax. Please could you show me how I should do with this code? Thank you!

Browser other questions tagged

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