Element update with JQuery with return from another script

0

I have a formulário de e-mail simples , and when I click "Send" the "status" appears next to the button, for example:

Enquanto envia , "Sending ..." appears (this is already working)

The problema is as follows: My form is in the "index", and action do form is in another "email.php" file.

How do I JQuery receive retorno of "email.php" and know if the email was sent or not, in order to update status

No index:

<script type="text/javascript">
        $(document).ready(function(){
            $('#email').submit(function() {
                $('#emlst').text('Enviando...');
                //if do retorno
            });
        });
    </script>
    
asked by anonymous 23.10.2017 / 16:18

2 answers

1

This is a mailing by ajax / jquery, see if you can understand it, it's very simple, it's commented on the important lines:

$(function() {
   $('#email').submit(function(ev) {
      ev.preventDefault(); //cancela a troca de página

      var formData = $('#email').serialize(); //Serializa o form em um post

      $('.btn-enviar').attr('disabled','disabled').css('cursor', 'wait'); //desativa o botão para não ficarem clicando
      $('#emlst').text('Enviando...'); //Altera a msg de envio

      $.ajax({
         type: 'POST',
         url: $('#email').attr('action'), //pega o link de action
         data: formData
      })
      .done(function(response) {
         var result = JSON.parse(response);

         $('#email')[0].reset(); //reseta o formulario
         $('.btn-enviar').removeAttr('disabled','disabled').css('cursor', 'pointer'); //retorna o botão para clicar

         $('#emlst').text('E-mail Enviado'); //Altera a msg caso enviado
      })
      .fail(function(data) {
         $('#emlst').text('Erro');
         $('.btn-enviar').removeAttr('disabled','disabled').css('cursor', 'pointer');
      });
   });
});
    
23.10.2017 / 16:32
1

I do not know if I understand very well, but if I understand, your code that sends the email is in another file, right? (that's what I understood with action do form ).

If it's really that simple, let's pretend you're using PHP to send the email.

$.ajax({
   type: 'POST',
   url: 'SEU ARQUIVO',
   data: $('#form').serialize(),
   dataType: 'json',
   beforeSend: function(){
       $('.msg').text('Enviando...')
   },
   success: function(data){
      $('.msg').text(data.msg)
   }
})

With this, we would already be sending the data to the form, in addition to changing the message, now we will see what would be the file PHP

<?php
   $retorno = array();

   // aqui vai todo o seu codigo de envio de email
   if($mail){
       $retorno['msg'] = 'Email enviado com sucesso';
   }else{
       $retorno['msg'] = 'Erro ao enviar email';
   }

   die(json_encode($retorno));
    
23.10.2017 / 16:25