I cannot send form data with AJAX

Asked

Viewed 247 times

1

I have a problem a few days, that with testing and research I’m not able to solve. My problem persists in a certain form send the data via AJAX to PHP treat and send an email, until then works without major problems. The additional is, when sending the data a message appears in the place in the form which I can also do.

The problem is: I can’t show the message and send the data by email. It’s like he’s doing something or other. Go to the main code below:

AJAX

$("#f_pre_cadastro").submit(function(e) {       

    var form_data = $(this).serialize();                    // Pega os dados do FORM
    var form_url = $(this).attr("action");                  // Pega o ACTION
    var form_method = $(this).attr("method").toUpperCase(); // POST ou GET

    $.ajax({
            url: form_url, 
            type: form_method,      
            data: form_data,     
            cache: false,                                   // força as páginas solicitadas a não serem armazenada em cache         
            success:  function(returnhtml){   
                if(returnhtml){
                    $("form").css({"display": "none"});
                    $('h2').html('Parabéns!'); 
                    $('p').html('Seus dados foram enviados com sucesso! <br> Aguarde nosso retorno por e-mail.');   
                }else{
                    window.alert('Erro!');
                }   
            }

    }); 

    //e.preventDefault();   
    //e.stopPropagation();
    return false;

});

PHP

if(isset($_POST["btnEnviar"]) && $_POST["nome_f"] != '' && isset($_POST["email_f"]) && $_POST["email_f"] != ''){

        $nome_f     = isset($_POST["nome_f"]) ? ucwords_improved(anti_injection($_POST["nome_f"])) : '';
        $email_f    = isset($_POST["email_f"]) ? anti_injection($_POST["email_f"]) : '';
        $whatsapp   = isset($_POST["whatsapp_f"]) ? anti_injection($_POST["whatsapp_f"]) : '';
        $empresa    = isset($_POST["empresa_f"]) ? anti_injection($_POST["empresa_f"]) : '';
        $cpfCnpj    = isset($_POST["cpfCnpj_f"]) ? anti_injection($_POST["cpfCnpj_f"]) : '';
        $finalidade = isset($_POST["finalidade_f"]) ? anti_injection($_POST["finalidade_f"]) : '';

        //envia email de solicitação de cadastro
        $email_destinatario    = '[email protected]';
        $subject   = 'Site - Novo Cadastro: ' . $nome_f;

        $body = '
        <p style="margin:10px 0; line-height:160%">
        <br>Olá, Moisés !
        <br><br>Você recebeu um novo e-mail de solicitação de cadastro!
        <br><br>Nome: ' . $nome_f . '
        <br><br>E-mail: ' . $email_f . '
        <br><br>WhatsApp: ' . $whatsapp . '
        <br><br>Empresa: ' . $empresa . '
        <br><br>CPF/CNPJ: ' . $cpfCnpj . '
        <br><br>Finalidade do Cadastro: ' . $finalidade . '        
        </p>';      


        $envioEmailSolicitacao = sendMail($nome_f, '[email protected]', $email_f, $email_destinatario, $subject, $body);

        if($envioEmailSolicitacao){
            $alerta   = 'Seus dados foram enviados com sucesso!';                          
        }else{
            $alerta   = 'Erro ao enviar e-mail. Tente novamente!';
        }

    }

HTML

<div class="section-block-parallax" id="comece-ja" style="background-image: url(<?php echo $config_base_path; ?>/img/cadastro.jpg);">
    <!-- Gradient Overlay START -->
    <div class="gradient-overlay"></div>
    <!-- Gradient Overlay END -->
    <div class="container">
        <div class="section-heading center-holder white-color wow fadeInDown animated">
            <h2>Cadastre-se</h2>
            <p>Preencha o formulário abaixo para nossa equipe fazer uma pré-análise dos seus dados. <br> Se seu cadastro for aceito, você receberá um link por e-mail para prosseguir.</p>
            <div class="section-heading-line"></div>
        </div>      
        <div class="center-holder wow fadeInUp animated mt-50" data-wow-delay=".3s">
            <form id="f_pre_cadastro" class="comment-form" method="post" action="<?php echo selfURL(); ?>">
                <?php
                if(isset($alerta)){
                    echo '<div class="row"><div class="col-sm-4 center-block"><p style="margin:0 0 20px 0; clear:both !important; color:#FFF"><strong>'. $alerta. '</strong></p></div></div> <script>window.alert("'. $alerta. '");</script>';
                }
                ?>  
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_nome">Seu nome</label> 
                        <input name="nome_f" id="f_nome" value="" required> <!-- 'f' é referente a finalidade do uso -->
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_email">Seu e-mail</label>
                        <div class="alerta">
                            <input name="email_f" id="f_email" type="email" value="" maxlength="100" required>
                            <p class="msg_alerta" id="msg_email_alerta"></p>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_whatsapp">Seu WhatsApp</label>
                        <div class="alerta">
                            <input name="whatsapp_f" id="f_whatsapp" type="" value="" maxlength="100" required>                         
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_empresa">Empresa</label>
                        <div class="alerta">
                            <input name="empresa_f" id="f_empresa" type="" value="" maxlength="100" required>                            
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_cpfCnpj">CPF/CNPJ</label>
                        <div class="alerta">
                            <input name="cpfCnpj_f" id="f_cpfCnpj" type="" value="" maxlength="100" required>                            
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <label for="f_finalidade">Qual a finalidade do seu cadastro ?</label>
                        <div class="alerta">
                            <textarea style="margin-top: 0;" name="finalidade_f" id="f_finalidade" type="" value="" maxlength="100" required></textarea>                            
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 center-block">
                        <button type="submit" name="btnEnviar" class="gradient-button button-sm" id="bt_submit">Enviar</button>
                    </div>                          
                </div>                

            </form>
        </div>

    </div>
</div>

Note: I was wondering what the 'Return false' of AJAX by disabling the 'objective' of 'Submit', it does not send the data, but I could not think of a logic to send the data by email and show the message without problems.

  • If you fixed the problem, post the solution as the answer, explain what was wrong and show why the solution solved the problem.

3 answers

0

Send using json_encode, your form is being sent, but the where you put it to show?

one echo in alerta would solve, but I recommend you do:

$(document).ready(function() {
  $("#f_pre_cadastro").submit(function(e) {       

    var form_data = $(this).serialize();                    // Pega os dados do FORM
    var form_url = $(this).attr("action");                  // Pega o ACTION
    var form_method = $(this).attr("method").toUpperCase(); // POST ou GET

    $.ajax({
            url: form_url, 
            type: form_method,      
            data: form_data,
            dataType: 'json',  
            cache: false,                                   // força as páginas solicitadas a não serem armazenada em cache         
            success:  function(returnhtml){   
                if(returnhtml.status == 'ok'){
                    $("form").css({"display": "none"});
                    $('h2').html('Parabéns!'); 
                    $('p').html(returnhtml.message);   
                }else if (returnhtml.status == 'fail'){
                    window.alert(returnhtml.message);
                }   
            }

    }); 

    //e.preventDefault();   
    //e.stopPropagation();
    return false;

  });
})

In PHP, to test I removed the validations you had, just add again, ok?

    <?php
if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST'){

  $nome_f = filter_input(INPUT_POST, 'nome_f');
  $email_f = filter_input(INPUT_POST, 'email_f');
  $whatsapp = filter_input(INPUT_POST, 'whatsapp');
  $empresa = filter_input(INPUT_POST, 'empresa');
  $cpfCnpj = filter_input(INPUT_POST, 'cpfCnpj');
  $finalidade = filter_input(INPUT_POST, 'finalidade');

  //envia email de solicitação de cadastro
  $email_destinatario    = '[email protected]';
  $subject   = 'Site - Novo Cadastro: ' . $nome_f;

  $body = '
  <p style="margin:10px 0; line-height:160%">
  <br>Olá, Moisés !
  <br><br>Você recebeu um novo e-mail de solicitação de cadastro!
  <br><br>Nome: ' . $nome_f . '
  <br><br>E-mail: ' . $email_f . '
  <br><br>WhatsApp: ' . $whatsapp . '
  <br><br>Empresa: ' . $empresa . '
  <br><br>CPF/CNPJ: ' . $cpfCnpj . '
  <br><br>Finalidade do Cadastro: ' . $finalidade . '        
  </p>';      


  $envioEmailSolicitacao = sendMail($nome_f, '[email protected]', $email_f, $email_destinatario, $subject, $body);

  if($envioEmailSolicitacao){
    echo json_encode(array(
      'status' => 'ok',
      'message' => 'Seus dados foram enviados com sucesso!'
    ));                          
  }else{
    echo json_encode(array(
      'status' => 'fail',
      'message' => 'Erro ao enviar e-mail. Tente novamente!'
    )); 
  }
  • No success unfortunately. With his option he does not even show the form to fill in the data. I tried to check some ; missing, and even put after json_encode function, but no return. Thanks

  • I made an edit, there were some mistakes

-1

Try using jquery to send the data, it looks like this:

$.post(form_url, form_data, function(returnhtml){
    if(returnhtml){
            $("form").css({"display": "none"});
            $('h2').html('Parabéns!'); 
            $('p').html('Seus dados foram enviados com sucesso! <br> Aguarde nosso retorno por e-mail.');   
        }else{
            window.alert('Erro!');
        }   
});
  • Thanks my friend, but unfortunately it didn’t work out. The result was that he showed the message and in a fraction of a second loaded the page (Returning to the page of the form) sending the data by e-mail. .

  • Dude you have want to give a feedback on your PHP page, so it can appear (echo $alert), and add the function "e. preventDefault();" in javascript

-1

PHP

<?php 
    if(isset($_POST["btnEnviar"]) && $_POST["nome_f"] != '' && isset($_POST["email_f"]) && $_POST["email_f"] != ''){

    $nome_f     = isset($_POST["nome_f"]) ? ucwords_improved(anti_injection($_POST["nome_f"])) : '';
    $email_f    = isset($_POST["email_f"]) ? anti_injection($_POST["email_f"]) : '';
    $whatsapp   = isset($_POST["whatsapp_f"]) ? anti_injection($_POST["whatsapp_f"]) : '';
    $empresa    = isset($_POST["empresa_f"]) ? anti_injection($_POST["empresa_f"]) : '';
    $cpfCnpj    = isset($_POST["cpfCnpj_f"]) ? anti_injection($_POST["cpfCnpj_f"]) : '';
    $finalidade = isset($_POST["finalidade_f"]) ? anti_injection($_POST["finalidade_f"]) : '';

    //envia email de solicitação de cadastro
    $email_destinatario    = '[email protected]';
    $subject   = 'Site - Novo Cadastro: ' . $nome_f;

    $body = '
    <p style="margin:10px 0; line-height:160%">
    <br>Olá, Moisés !
    <br><br>Você recebeu um novo e-mail de solicitação de cadastro!
    <br><br>Nome: ' . $nome_f . '
    <br><br>E-mail: ' . $email_f . '
    <br><br>WhatsApp: ' . $whatsapp . '
    <br><br>Empresa: ' . $empresa . '
    <br><br>CPF/CNPJ: ' . $cpfCnpj . '
    <br><br>Finalidade do Cadastro: ' . $finalidade . '        
    </p>';      


    $envioEmailSolicitacao = sendMail($nome_f, '[email protected]', $email_f, $email_destinatario, $subject, $body);

    if($envioEmailSolicitacao){
        $alerta   = 'Seus dados foram enviados com sucesso!';

    }else{
        $alerta   = 'Erro ao enviar e-mail. Tente novamente!';

    }
    return $alerta;
    }
?>

AJAX

$("#f_pre_cadastro").submit(function(e) {       

var form_data = $(this).serialize();                    // Pega os dados do FORM
var form_url = $(this).attr("action");                  // Pega o ACTION
var form_method = $(this).attr("method").toUpperCase(); // POST ou GET

$.ajax({
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,                                   // força as páginas solicitadas a não serem armazenada em cache         
        success:  function(returnhtml,msg){   
            if(returnhtml){
                $("form").css({"display": "none"});
                $('h2').html('Parabéns!'); 
                $('p').html('Seus dados foram enviados com sucesso! <br> Aguarde nosso retorno por e-mail.');

            }
             alert(msg);
        },
        error: function(){
            return false;

        }

}); 

//e.preventDefault();   
//e.stopPropagation();
return false;
});

Try it like this, I used the return and echo in PHP to prevent errors, and I also used the attribute error in the AJAX

  • Thank you Dbaalone. Your partially worked out. He sent the email, showed the stylized message in place of the form and after that he loads the page. Displaying the PHP echo message and no longer the stylized message.

  • I am happy to have helped, can you mark as concluded? ecaso you can remove echo, I did more for precaution, in case the Return did not work.

  • So my friend, I made your changes and partially understood. It shows the message quickly and loads the page does not show anything, I will send you the link of the application so you have a notion: https://linkto.bio/

  • I could not verify the error, a moment I will change the response and see if it helps

  • Check this link where it shows the timeout part, where js waits a certain time to continue. https://www.gigasystems.com.br/artigo/17/como-definir-o-tempo-de-atraso-em-javascript

  • The result is expected, but it does not send the form with this last false Return. I am tracking the console in the network tab where it shows the AJAX request. What I understood there is that with this last Return it holds the index(linkto.bio), in the other way when it sends the form to the email, it holds for a moment and sends the same, at that moment of instants is shown the message. Regarding the timeout is that it after a moment will reload the page, thus showing the form again that is not the requirement, unfortunately.

Show 1 more comment

Browser other questions tagged

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