Success message after completing the PHP form

Asked

Viewed 4,895 times

5

I’m trying to create a simple form for logging a visit at a location. However, I am unable to place a "Data Successfully Sent" message on the same page of this form. The validation of this form, before sending to the Database, I did in PHP, according to the code below:

form_contact.php

<?php

?>
<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>contato</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
    </head>
    <head>
    <body>
            <div class="container">

        <form class="form-horizontal" method="POST" action="salva_mensagem.php">
        <div class="form-group">
                    <label for="inputEmail3" class="col-sm-2 control-label">Nome</label>
                    <div class="col-sm-10">
                        <input type="text" name="nome" class="form-control" placeholder="Nome Completo" required>
                    </div>
                    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                                        <div class="col-sm-10">
                        <input type="mail" name="email" class="form-control" placeholder="Seu EMail" required>
                    </div>
          <label for="inputEmail3" class="col-sm-2 control-label">Telefone</label>
          <div class="col-sm-10">
              <input type="text" name="assunto" class="form-control" placeholder="Telefone" required>
          </div>
                    </div>
<div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <center><button type="submit" value="Enviar" class="btn btn-success" >Enviar</button></center>
                    </div>
          </div>

    </form>
    </div>
    </body>
</html>

salva_mensagem.php

<?php
    include_once('conexao.php');
    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $assunto = $_POST['assunto'];
    $mensagem = $_POST['mensagem'];

    $result_msg_contato = "INSERT INTO mensagens_contatos(nome, email, assunto, mensagem, created) VALUES ('$nome', '$email', '$assunto', '$mensagem', NOW())";
    $resultado_msg_contato= mysqli_query($conn, $result_msg_contato)

?>
  • Do not use Code snippet (Stack Snippets) for PHP, read: http://meta.pt.stackoverflow.com/q/2115/3635

6 answers

2

You can display a successful Alert, I think you can do so

if($resultado_msg_contato->rowcount()<=0){
    echo '<script>alert("Ocorreu um erro!!"); </script>';
}else{
    echo '<script>alert("Dados enviados com sucesso!!"); </script>';
}

2

First of all make a check of the mysqli_query, for this use the mysqli_error($conn):

if ($resultado_msg_contato) {
    //Mensagem de successo
} else {
    //Mensagem de erro com mysqli_error($conn)
}

You can then send the POST pro same address and making use of if and isset, let the action="" empty like this:

<form class="form-horizontal" method="POST" action="">

The whole code should look like this:

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>contato</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
    </head>
    <head>
    <body>
            <div class="container">
    <?php

    if (isset($_POST['nome'], $_POST['email'], $_POST['assunto'], $_POST['mensagem'])) {
        include_once('conexao.php');

        $nome = $_POST['nome'];
        $email = $_POST['email'];
        $assunto = $_POST['assunto'];
        $mensagem = $_POST['mensagem'];

        $result_msg_contato = "INSERT INTO mensagens_contatos(nome, email, assunto, mensagem, created) VALUES ('$nome', '$email', '$assunto', '$mensagem', NOW())";
        $resultado_msg_contato= mysqli_query($conn, $result_msg_contato);

        if ($resultado_msg_contato) {
            echo '<div class="alert alert-success">Dados enviado com Sucesso!</div>';
        } else {
            echo '<div class="alert alert-danger">Erro:', mysqli_error($conn),'</div>';
        }
    }
    ?>
        <form class="form-horizontal" method="POST" action="">
        <div class="form-group">
                    <label for="inputEmail3" class="col-sm-2 control-label">Nome</label>
                    <div class="col-sm-10">
                        <input type="text" name="nome" class="form-control" placeholder="Nome Completo" required>
                    </div>
                    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                                        <div class="col-sm-10">
                        <input type="mail" name="email" class="form-control" placeholder="Seu EMail" required>
                    </div>
          <label for="inputEmail3" class="col-sm-2 control-label">Telefone</label>
          <div class="col-sm-10">
              <input type="text" name="assunto" class="form-control" placeholder="Telefone" required>
          </div>
                    </div>
<div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <center><button type="submit" value="Enviar" class="btn btn-success" >Enviar</button></center>
                    </div>
          </div>

    </form>
    </div>
    </body>
</html>

Or using Ajax

You can use Ajax (XmlHttpRequest) combined with addEventListener("submit", ...) to send the form and treat the response in the callback:

var oReq = new XMLHttpRequest();

//Defina como true
oReq.open("POST", form.getAttribute("action"), true);

//Função assíncrona que aguarda a resposta
oReq.onreadystatechange = function()
{
    //Se 4 é que concluiu
    if (oReq.readyState === 4) {

        //Checa o status HTTP
        if (oReq.status >= 200 && oReq.status < 300) {
            if (oReq.responseText === "sucesso") {
                alert("Dados enviados com sucesso");
            } else {
                alert("Erro:" + oReq.responseText);
            }
        } else {
            alert("Erro HTTP:" + oReq.status);
        }
    }
};

oReq.send(new FormData(form)); //Envia os campos com a API

The salva_mensagem.php should look like this:

<?php

if (isset($_POST['nome'], $_POST['email'], $_POST['assunto'], $_POST['mensagem'])) {
    include_once('conexao.php');

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $assunto = $_POST['assunto'];
    $mensagem = $_POST['mensagem'];

    $result_msg_contato = "INSERT INTO mensagens_contatos(nome, email, assunto, mensagem, created) VALUES ('$nome', '$email', '$assunto', '$mensagem', NOW())";
    $resultado_msg_contato= mysqli_query($conn, $result_msg_contato);

    if ($resultado_msg_contato) {
        echo 'sucesso';
    } else {
        echo 'Erro:', mysqli_error($conn);
    }
}
?>

Should stay like this:

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>contato</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
    </head>
    <head>
    <body>
        <div class="container">
        <form id="meuform" class="form-horizontal" method="POST" action="salva_mensagem.php">
        <div class="form-group">
                    <label for="inputEmail3" class="col-sm-2 control-label">Nome</label>
                    <div class="col-sm-10">
                        <input type="text" name="nome" class="form-control" placeholder="Nome Completo" required>
                    </div>
                    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                                        <div class="col-sm-10">
                        <input type="mail" name="email" class="form-control" placeholder="Seu EMail" required>
                    </div>
          <label for="inputEmail3" class="col-sm-2 control-label">Telefone</label>
          <div class="col-sm-10">
              <input type="text" name="assunto" class="form-control" placeholder="Telefone" required>
          </div>
                    </div>
<div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <center><button type="submit" value="Enviar" class="btn btn-success" >Enviar</button></center>
                    </div>
          </div>
    </form>
    </div>

        <script type="text/javascript">
        function EnviarForm(e) {
            //Previne enviar o Form normal
            e.preventDefault();

            //Pega o form
            var form = e.target;

            //Previne enviar múltiplas vezes até que o Ajax complete
            if (form.enviando) {
                return;
            }

            form.enviando = true;

            var oReq = new XMLHttpRequest();

            //form.getAttribute("action") é para pegar o action do Form
            oReq.open("POST", form.getAttribute("action"), true);

            //Função assíncrona que aguarda a resposta
            oReq.onreadystatechange = function()
            {
                if (oReq.readyState === 4) {

                    //desbloqueia o form
                    form.enviando = false;

                    if (oReq.status >= 200 && oReq.status < 300) {
                        if (oReq.responseText === "sucesso") {
                            alert("Dados enviados com sucesso");
                        } else {
                            alert("Erro:" + oReq.responseText);
                        }
                    } else {
                        alert("Erro HTTP:" + oReq.status);
                    }
                }
            };

            oReq.send(new FormData(form)); //Envia os campos com a API FormData
        }

        document.getElementById("meuform").addEventListener("submit", EnviarForm);
        </script>
    </body>
</html>

0

0

The question post a "Data Successfully Sent" on the same page of this form.

just put onSubmit="alert('Dados enviado com Sucesso.');" >

in form

<form class="form-horizontal" method="POST" action="salva_mensagem.php" onSubmit="alert('Dados enviado com Sucesso');">

example

<form class="form-horizontal" method="POST" action="/unanswered/tagged/?tab=newest" onSubmit="alert('Dados enviado com Sucesso');">
        <div class="form-group">
					<label for="inputEmail3" class="col-sm-2 control-label">Nome</label>
					<div class="col-sm-10">
						<input type="text" name="nome" class="form-control" placeholder="Nome Completo" required>
					</div>
                    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                                        <div class="col-sm-10">
						<input type="mail" name="email" class="form-control" placeholder="Seu EMail" required>
					</div>
          <label for="inputEmail3" class="col-sm-2 control-label">Telefone</label>
          <div class="col-sm-10">
			  <input type="text" name="assunto" class="form-control" placeholder="Telefone" required>
		  </div>
					</div>
<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						<center><button type="submit" value="Enviar" class="btn btn-success" >Enviar</button></center>
					</div>
		  </div>

	</form>

0

You can set a notification balloon with this message!

At the end of php code, refresh the page and send the url &f=1

In the text balloon, add if(isset($_GET['f'])) and target the intended message!

In steps

  1. Create balloon, recommend using bootstrap with position: fixed; right: 10px; bottom:10px; in styles.
  2. Use <meta refresh> or header('Location: link_do_site'); and add &f=1
  3. And finally, before where the div of alert, add if(isset($_GET['f'])){.

This way it will be pleasant to the view and quite practical!

0

If you put this script on your page, an Alert will appear warning you that you have been saved and then return to the previous page. :)

salva_mensagem.php

<?php

    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $assunto = $_POST['assunto'];
    $mensagem = $_POST['mensagem'];

    $strcon = mysqli_connect('localhost','root','', 'seu_banco') or die('Erro ao conectar ao banco de dados');
    $sql = "INSERT INTO mensagens VALUES ('$nome', '$email', '$assunto', '$mensagem')"; 
    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
    mysqli_close($strcon);

    echo '<script type="text/javascript">
            alert("Salvo com Sucesso !");
            window.history.go(-1);
        </script>';

?>

Browser other questions tagged

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