Phrase "Email sent successfully" on the same page of the Form. How to configure?

Asked

Viewed 2,485 times

-1

I have seen forms with the notice of "E-mail sent successfully" on the same page of the form after its submission. my form worked well when I made the php file separately and in the form I called it: action="send.php".

But I find it more interesting the user not to be white screens or additional screens without precision. So I tried to direct my action to the same page: action="#". But then I had all the variables as waved. I tried to solve it and I couldn’t, Where is the mistake? I imagine it must be something simple.

The code is a functional comment system, but I searched for adaptations to transfer the sentence to the same page, so it stopped working.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Classificdos</title>
</head>
<style>
    div#container{
        width: 50%;
        text-align: justify;
        background: blue;
        margin:0 auto;
        font-family: helvetica;
        padding: 3%;
    }
</style>
<body>
    <div id="container">
        <h1>NOTICIA DO DIA</h1>

        <hr/>


        <h3>Deixe seu comentário</h3>

        <?php 
        //error_reporting(0);
    if(isset($_POST['comentar'])){
        $nome =         $_POST['nome'];
        $email =        $_POST['email'];
        $site =         $_POST['site'];
        $comentario =   $_POST['comentario'];
        $identificacao= $_POST['identificacao'];
        $moderacao =    $_POST['moderar'];
    }
        if(isset($_FILES['avatar']))
   {
      date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

      $ext = strtolower(substr($_FILES['avatar']['name'],-4)); //Pegando extensão do arquivo
      $new_name = date("Y.m.d-H.i.s") . $ext; //Definindo um novo nome para o arquivo
      $dir = 'uploads/'; //Diretório para uploads

      move_uploaded_file($_FILES['avatar']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo
  }


        $headers = "Content-type:text/html; charset=UTF-8";
        $headers = "From: $email";
        $para    = "[email protected]";
            $mensagem = "De: $nome";
            $mensagem .= "E-mail: $email";
            $mensagem .= "Site: $site";
            $mensagem .= "Comentario: $comentario";



        $envia = mail($para, "Comentário Efetuado no site", $mensagem, $headers);


        $insere = ("INSERT INTO comentarios (id, nome, email, site, comentario, identificacao, moderacao, avatar ) VALUES ('NULL', '$nome', '$email', '$site', '$comentario', '$identificacao', '$moderacao', '$new_name')"); //new_name e o novo nome da $avatar defidido por horas.

        $insereBanco = mysql_query($insere);

            echo "<p><strong>$nome</strong>, seu comentário foi efetuado com sucesso e aguarda liberação. Obrigado!";
            echo "<p><a href='Sistema_comentarios.php'>Voltar</a></p>";

        ?>

        <form id="" action="" method="post" enctype="multipart/form-data">
            <fieldset>
                <legend>Preencha os Campos Abaixo:</legend>

                    <label for="nome">NOME: </label>
                        <input type="text" required id="nome" name="nome">
                            <div class="clear"></div>

                    <label for="email">E-MAIL: </label>
                        <input type="text" id="email" name="email">
                            <div class="clear"></div>

                    <label for="site">SITE (Opcional): </label>
                        <input type="text" id="site" name="site">
                            <div class="clear"></div>
                    <label for="comentario">Deixe seu Comentário</label><br/>
                        <textarea name="comentario" id="comentario" cols="60" rows="10"></textarea>

                    <label id="escolher_foto" for="foto">Escolher uma Foto</label>
                     <input type="file" name="avatar" id="avatar" required="">

                    <input type="submit" value="Comentar"><br/>
                    <input type="hidden" name="identificacao" value="1"/>
                    <input type="hidden" name="moderar" value="nao"/>
            </fieldset>
        </form>
    </div>


</body>
</html>
  • 1

    I have already edited two of your questions and put the notice http://answall.com/revisions/115563/3 and http://answall.com/revisions/115424/2, please pay more attention, The snippet stack is obviously used to run javascript, html and css, that is front-end, there is no reason to use stacksnippet to put php, c++, java, c#, it will never work. Use normal markup if only to display codes.

  • I’m sorry. When Voce speaks the stack snippet is in the question options the "Snippet" button and the normal markup that Oce tells me to use is the "Code Sample" button? because I want to do it the right way.

  • yes the "chunk" is itself, really the translation is weird, understand so the "chunk" should be used when the code can be executed, as an execution of a "javascript" or an html+css effect, or an HTML5 tag that is not working in a given browser. PHP, C#, C/C++ cannot run in stacksnippets. In case you just want to show the code, use the "code sample"...

  • ... Sorry is not wanting to criticize you, far from it, but the button "snippet" appears like this trecho javascript/html/css ctrl+m, Isn’t that clear enough? It’s not bad that I ask, is that I’m trying to propose to Adms a change in layout because many get confused, even though it seems obvious, I would like to understand what led you to confuse to suggest a solution in the meta.stackexchange.

  • I understand it is quiet. I will answer you... I put because the files I sent contain html, so much so that it has the Html5 tag. In this case I looked at the whole button bar and I didn’t see anything about PHP, I thought not to err more ugly and put in css or javascript, it was obvious to me that the only remaining option was html. But it was for lack of information on the bar. I did not associate my complete code as a sample only.

  • but what is the problem is HTML that can be reproduced, if the idea is just to show the HTML and not to reproduce an "HTML" problem then there is no reason to use stacksnippet, I think the problem is that few understand what is stacksnippet or jsfiddle, recommend reading: https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/ and http://meta.stackoverflow.com/questions/269753/feedback-requested-runnable-code-snippets-in-questions-and-answers

  • Did you read my reply, about the use of isset?

Show 2 more comments

2 answers

3

The use of if ($_SERVER['REQUEST_METHOD'] === 'POST') { is no guarantee, there may be flaws in the script if you use it or just it, as somehow the html form fails or missing some field and still can be sent, but missing "inputs", I recommend you use isset or empty, as I explained in this reply /a/63550/3635

A way to use the isset

<?php
//Inicia o IF
if (isset($_POST['nome'], $_POST['email'], $_POST['site'], $_POST['comentario'], $_POST['identificacao'], $_POST['moderar'], $_POST['comentar']))
{

    $nome =         $_POST['nome'];
    $email =        $_POST['email'];
    $site =         $_POST['site'];
    $comentario =   $_POST['comentario'];
    $identificacao= $_POST['identificacao'];
    $moderacao =    $_POST['moderar'];

    if(isset($_FILES['avatar']))
    {
        date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

        $ext = strtolower(substr($_FILES['avatar']['name'],-4)); //Pegando extensão do arquivo
        $new_name = date("Y.m.d-H.i.s") . $ext; //Definindo um novo nome para o arquivo
        $dir = 'uploads/'; //Diretório para uploads

        move_uploaded_file($_FILES['avatar']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo
    }


        $headers = "Content-type:text/html; charset=UTF-8";
        $headers = "From: $email";
        $para    = "[email protected]";
            $mensagem = "De: $nome";
            $mensagem .= "E-mail: $email";
            $mensagem .= "Site: $site";
            $mensagem .= "Comentario: $comentario";



        $envia = mail($para, "Comentário Efetuado no site", $mensagem, $headers);


        $insere = ("INSERT INTO comentarios (id, nome, email, site, comentario, identificacao, moderacao, avatar ) VALUES ('NULL', '$nome', '$email', '$site', '$comentario', '$identificacao', '$moderacao', '$new_name')"); //new_name e o novo nome da $avatar defidido por horas.

        $insereBanco = mysql_query($insere);

            echo "<p><strong>$nome</strong>, seu comentário foi efetuado com sucesso e aguarda liberação. Obrigado!";
            echo "<p><a href='Sistema_comentarios.php'>Voltar</a></p>";

} //Termina o IF
?>

I recommend you read the documentation: http://php.net/manual/en/function.isset.php

1


You just need to encapsulate your PHP code that deals with receive the POST parameters and save to the bank and send the email within the following IF:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // seu código vai aqui
}

Thus, if your user only enters your page through the URL, the $_SERVER['REQUEST_METHOD'] will equal "GET", you will not perform any operation in PHP and just display the comments page to it, HTML.

And when your user submits the comments form, $_SERVER['REQUEST_METHOD'] will equal "POST" and then yes your PHP code from email + save to DB + message that the comment was saved from will run. It follows how your PHP should stay inside the file:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //error_reporting(0);
    if(isset($_POST['comentar'])){
        $nome =         $_POST['nome'];
        $email =        $_POST['email'];
        $site =         $_POST['site'];
        $comentario =   $_POST['comentario'];
        $identificacao= $_POST['identificacao'];
        $moderacao =    $_POST['moderar'];
    }

    if(isset($_FILES['avatar'])) {
        date_default_timezone_set("Brazil/East"); //Definindo timezone padrão

        $ext = strtolower(substr($_FILES['avatar']['name'],-4)); //Pegando extensão do arquivo
        $new_name = date("Y.m.d-H.i.s") . $ext; //Definindo um novo nome para o arquivo
        $dir = 'uploads/'; //Diretório para uploads

        move_uploaded_file($_FILES['avatar']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo
    }

    $headers = "Content-type:text/html; charset=UTF-8";
    $headers = "From: $email";
    $para    = "[email protected]";
    $mensagem = "De: $nome";
    $mensagem .= "E-mail: $email";
    $mensagem .= "Site: $site";
    $mensagem .= "Comentario: $comentario";

    $envia = mail($para, "Comentário Efetuado no site", $mensagem, $headers);

    $insere = ("INSERT INTO comentarios (id, nome, email, site, comentario, identificacao, moderacao, avatar ) VALUES ('NULL', '$nome', '$email', '$site', '$comentario', '$identificacao', '$moderacao', '$new_name')"); //new_name e o novo nome da $avatar defidido por horas.

    $insereBanco = mysql_query($insere);

    echo "<p><strong>$nome</strong>, seu comentário foi efetuado com sucesso e aguarda liberação. Obrigado!";
    echo "<p><a href='Sistema_comentarios.php'>Voltar</a></p>";
}
?>
  • Taylan, the ``is for code, for highlighting text, you can use bold or Italic.

  • 1

    @Diegof Blz, hadn’t even thought about. Vlws by fix.

  • @tayllan perfect, it was exactly this, and his reply pointed out to me another small flaw that resulted in the functioning of the code, thank you very much.

Browser other questions tagged

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