PHP and Javascript - Show alert without updating page

Asked

Viewed 1,678 times

0

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

<?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ção de material de Marketing:</div>
                <br><br>Unidade: '.$unidade.'
                <br>Solicitante: '.$solicitante.'
                <br><br>Campanha Escolhida: '.$campanha.'
                <br><br><img src="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;
    }
    }
}

Code of the btnEnvia button:

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

The problem is that, in my case, the page is automatically updated and then the alert appears. And in that refresh, he misses what I’ve already filled in from the beginning.

How could I make sure this refresh doesn’t happen and give me the alert smoothly?

  • instead of type=Ubmit switch to button

  • Another tip is not to display sensitive content of your business in the example. Let’s say the connection credentials of smtp from the hotels. But if they are fake. Ok.

  • It didn’t work, @Marconi. Then the button doesn’t work at all.

  • Is jquery an option for you? Or do you prefer javascript "pure"?

  • @Gustavohoppelevin Does not work or submit the form?

  • @Moykn may be both. Which suggests?

  • @Marconi Do not submit

  • You can validate with this type of button, and use jquery’s Ubmit to submit your form. https://api.jquery.com/submit/

  • If I understand correctly, you want to send the form information and keep what you typed after Alert, your button is PHP, it sends the page information (Client) to the server and returns an HTML page as a result, in PHP it is possible to save the information in a variable $_POST or $_GET and then set the data in the result page on the server side. Or you can use Java for this, in which case you will NOT use the Submit button to send information to the server.

  • Man, this is lame, send a alert() Besides being unpleasant for the user, he doesn’t even know which are the two fields with empty value. I think you should review your form as there are several problems.

Show 5 more comments

2 answers

2

Using jQuery.

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

Calling e.preventDefault(); Prevents Submit from running, thus avoiding the post.

  • +1 good answer, I had forgotten about preventDefault.

  • Quiet. We forgot. It’s been a while since I used code like this. :)

0

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

The only difference is that replacing Submit with a button in your PHP code will no longer work: if(isset($_POST['btnEnvia'])){

You can exchange btnEnvia isset for any 1 of the fields in your form.

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

Anyway...there are several possibilities.

Browser other questions tagged

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