Success message after completing PHP form

5

I'm trying to create a simple form to record a visit in one place. However, I'm not able to put a "Successfully submitted data" message on the same page as 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>

save_message.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)

?>
    
asked by anonymous 04.10.2017 / 17:01

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>';
}
    
04.10.2017 / 17:16
1

First of all do a check of mysqli_query , so use mysqli_error($conn) :

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

You can then send POST to the same address and make use of if and isset , leave 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 handle 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);
    }
}
?>

It 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">
        <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>
    
04.10.2017 / 20:24
0

You can do as follows, within your PHP, just put.

echo 'Successfully uploaded data';

Remembering that anything else you are going to print inside your php on the display screen, just echo the string or variable.

Here is an example of the gringos friends.

link

    
04.10.2017 / 17:13
0

The question put a "Successfully submitted data" message on the same page as this form .

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

no 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="https://pt.stackoverflow.com/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>
    
04.10.2017 / 17:51
0

You can set a notification balloon with this message!

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

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

By steps
  • Creating balloon, I recommend using bootstrap with position: fixed; right: 10px; bottom:10px; in styles.
  • Use <meta refresh> or header('Location: link_do_site'); and add &f=1
  • And finally, before you get to div of alert , add if(isset($_GET['f'])){ .
  • This way it will be pleasing to the eye and quite practical!

        
    04.10.2017 / 18:19
    0

    If you put this script on your page, an alert will appear warning you that it has been saved and then back to the previous page. :)

    save_message.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>';
    
    ?>
    
        
    04.10.2017 / 20:03