Newsletter with refresh ajax

Asked

Viewed 75 times

0

I’m trying to send this form through ajax and I’m not getting, is there something wrong? I’m beating my head against this for four hours without success.

Note: I am developing via wordpress and I am using a plugin called Newsletter to store the emails captained by the form. I already managed to make it work once, but in another office and on another site, but I ended up losing the code that works and I’m trying again to make it work.

        var fmr = $('#formsnewslatetr');
        var dados = $('#formsnewslatetr').serialize();
        fmr.submit(function (e){
             e.preventDefault();

             $.ajax(
           {
               type: fmr.attr('method'),
               url: fmr.attr('action'),
               data: dados,
               success: function ( response )
               {
                   $('.success-box').fadeIn();
                   var retorno = 'true';
                   fmr.fadeOut();

                },
               error: function ( txt )
               {
                   alert( "ERRO" );
               }
           }
       );
}); 
<form id="formsnewslatetr" method="post" action="/?na=s" onsubmit="return newsletter_check(this)" class="form-inline w-100">
    <div class="form-group w-100">
          <input class="i-email" type="email" name="ne" id="email" placeholder="Email" required="">
          <input class="b-email" type="submit" value="Assinar">
    </div>
</form>

1 answer

1

The form is being submitted via button submit passing through function newsletter_check(this) waiting for a return. In this case, the fmr.submit (because if it was in memory -- it is not in memory because it seems to be inside a function that has not yet been executed --, the form would be sent 2x: one by the button submit and another by frm.submit).

In this case it is still necessary to put a return false; at the end of the function to prevent the page from being redirected.

In view of this, your code should have this structure:

function newsletter_check(formulario){ // o parâmetro "formulário" apenas como exemplo
   var fmr = $('#formsnewslatetr');
   var dados = $('#formsnewslatetr').serialize();
   $.ajax({
      type: fmr.attr('method'),
      url: fmr.attr('action'),
      data: dados,
      success: function(response){
         $('.success-box').fadeIn();
         var retorno = 'true';
         fmr.fadeOut();
      },
      error: function(txt){
         alert( "ERRO" );
      }
   });
   return false;
}

If you want to do some kind of e-mail validation, just put this validation at the beginning of the function and if it is not validated, add return false; to prevent the function from entering Ajax.

Browser other questions tagged

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