PHP and Javascript - Show alert without refreshing the page

0

I have a button on my page that sends e-mail with some information filled out. However, if two of the fields are empty, the browser gives an alert warning (indicated in the code below in ALL).

<?php
if(isset($_POST['btnEnvia'])){
    $unidade        = $_POST['unidade'];
    $solicitante    = $_POST['solicitante'];

    $campanha       = str_replace("chkCamp","Campanha ",$_POST['campanhaNome_enviar']);
    $layout         = str_replace("chkCamp","img",$_POST['campanhaNome_enviar']);

    $qtdBanner      = $_POST['qtdBanner'];
    $qtdCartaz      = $_POST['qtdCartaz'];
    $qtdOutdoor     = $_POST['qtdOutdoor'];
    $qtdFlyer       = $_POST['qtdFlyer'];
    $qtdEmail       = $_POST['qtdEmail'];

    $texto1         = $_POST['texto1'];

    // TODO Este alerta está fazendo refresh na página!!!
    if(($solicitante == "") or ($texto1 == "")){
        echo "<script language='javascript'>
            alert('Há campos não preenchidos!');
        </script>";
        return false;
    }
    else{

    require 'phpmailer/class.phpmailer.php';

    $mail = new PHPMailer();
    $mail->IsSMTP(); // send via SMTP
    $mail->Host = 'mail.meuservidor.com.br'; // SMTP servers
    $mail->Port = 25; // SMTP servers
    $mail->SMTPAuth = true; // turn on SMTP authentication
    $mail->Username = '[email protected]'; // SMTP username
    $mail->Password = 'senha@123'; // SMTP password
    $mail->From = '[email protected]';
    $mail->FromName = $solicitante;
    $mail->AddAddress('[email protected]');
    $mail->IsHTML(true); // send as HTML

    $mail->Subject = 'Solicitação de Material de Marketing - Unidade ' . $unidade;

    // corpo da mensagem
    $mail->Body = '<html>
        <body>
            <div style="font-family: Trebuchet MS; font-size: 16px;">
                <div style="text-align: center; font-family: Trebuchet MS; font-size: 16px;"><img src="http://minhaurl.png"></img><br><br>SolicitaçãodematerialdeMarketing:</div><br><br>Unidade:'.$unidade.'<br>Solicitante:'.$solicitante.'<br><br>CampanhaEscolhida:'.$campanha.'<br><br><imgsrc="minhaurl.png">
                <br><br>Briefing: '.$texto1.'
                <br><br>Material:
                <br>* Banner: '.$qtdBanner.'
                <br>* Cartaz: '.$qtdCartaz.'
                <br>* Outdoor: '.$qtdOutdoor.'
                <br>* Flyer: '.$qtdFlyer.'
                <br>* E-mail: '.$qtdEmail.'
            </div>
        </body>
    </html>';

    // corpo da mensagem em modo texto
    $mail->AltBody = 'Mensagem em texto';

    // verifica se enviou corretamente
    if ( $mail->Send() ) {
        echo "<script>
            alert('Pedido enviado!');
        </script>";
    }
    else {
        echo 'Erro do PHPMailer: ' . $Mailer->ErrorInfo;
    }
    }
}

Button Code btnSubmit:

<input name="btnEnvia" type="submit" value="Enviar" style="font-family: Trebuchet MS; font-size: 20px" /><

The problem is that, in my case, the page refreshes automatically and then the alert appears. And in this refresh, it loses what I have already filled in data, coming back from the beginning.

How could I make this refresh not happen and give me the alert without problems?

    
asked by anonymous 28.10.2015 / 17:35

2 answers

2

Using jQuery.

$("form").on("submit", function(e){
        if($("#solicitante").val()==="" || $("#texto1").val()===""){
            e.preventDefault();
            alert("Preencha todos os campos");                
        }
});

Call the e.preventDefault (); Prevents the submit from running, thus avoiding the post.

    
28.10.2015 / 18:05
0

You can do what Moykn suggested or change type='submit' to type='button'

The only difference is that by changing the submit by button, in your PHP code, this will no longer work: if(isset($_POST['btnEnvia'])){

You can change the isset of btnNext to any of the fields in your form.

Ah, of course also switching from submit to button, you need to use JS to submit the form.

Anyway ... there are several possibilities.

    
28.10.2015 / 18:17