Newsletter with refresh ajax

0

I'm trying to send this form via ajax and I'm not getting it, is something wrong? I'm banging my head on it, you love it for four hours without success.

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

        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>
    
asked by anonymous 27.01.2018 / 17:44

1 answer

1

The form is being submitted via submit button passing through the newsletter_check(this) function that expects a return . In this case, the fmr.submit becomes unnecessary (even because if it were 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 submit button % and another by frm.submit ).

In this case, you must still place a return false; at the end of the function to prevent the page from being redirected.

Given 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 validation of the email, just put this validation at the beginning of the function and if it is not validated, add return false; so that the function does not enter Ajax.

    
27.01.2018 / 19:27