Browser response after sending an email with PHP

2

I want to give an answer to the user, either: "Sent" or "Could not send" on the same page you see, after sending an email using a form ... Let me explain:

1: The user enters > Contact.html in the browser, fill in the form and click on the send button, so that:

I have attached the html5 code:

<form id="formulario" action="php/sendEmail.php" method="POST">                 
    <fieldset class="txtCentral txtDerecha">                
        <input type="text" id="nombre" class="fade inForm" name="nombre_txt" placeholder="Nombre *" required/>      
        <input type="text" id="apellido" class="fade inForm" name="apellido_txt" placeholder="Apellido"/>           
        <input type="email" id="email" class="fade inForm" name="email_txt" placeholder="Email *" required/>        
        <input type="text" id="asunto" class="fade inForm" name="asunto_txt" placeholder="Asunto"/>     
        <textarea id="mensaje" class="fade inForm" name="mensaje_txt" cols="31" rows="6" placeholder="Comentarios *" required></textarea>           
        <p class="txtRotulo">* Campos obligatorios.</p>     
        <div class="botonCentro">
            <input type="submit" id="enviar" class="fade botonLink" name="enviar_btn" value="Enviar"/>
        </div>      
    </fieldset>
</form>     
<div class="txtCentral" id="respuestaCorreo"></div>

2: The user expects the operation to send the mail, once the operation is done ... Well, as you can see, my intention is to put text in that "div" that has id="mailresponse" (The last line of the html5 code).

But add that text ... that breaks my head ... since I have to do it from php / sendEmail.php (location / NombreFichPHP), come on, from the php code.

The code in php is such that:

<?php    
    /* Variables de fichero PHP. */
    $destinatario = '[email protected]';
    /* variables de formulario necesarias. */
    $nombre = $_POST['nombre_txt'];    
    $email = $_POST['email_txt'];    
    $mensaje = $_POST['mensaje_txt']; 
    /* Variables de formulario opcionales. */
    $apellido = $_POST['apellido_txt'];
    $asunto =  $_POST['asunto_txt'];

    /* Comprobamos valores. */
    if(isset($nombre) && !empty($nombre) &&
        isset($email) && !empty($email) &&
        isset($mensaje) && !empty($mensaje)){

        /* Dar valores a las variables auxiliares si estan vacías. */
        if(isset($apellido) && empty($apellido)){
            $apellido = "";
        }else{
            /* Lo concatamos con el nombre. */
            $nombre .= " ".$apellido;
        }

        if(isset($asunto) && empty($asunto)){
            $asunto = "Sin asunto";
        }

        /* Generamos contenido del correo*/
        $contenido = "        
            <!DOCTYPE html>
            <html lang='en'>
            <head>
                <meta charset='UTF-8'>
            </head>
            <body>
                <header>
                    <h1>Correo</h1>
                </header>
                <div>
                    <P>Usuario: ".$nombre."</p>
                    <p>Correo: ".$email."</p>
                    <p>Mensaje: ".$mensaje."</p> 
                </div>
            </body>
            </html>
        ";

        /* Generamos la cabecera del correo. */
        $cabecera = "MIME-Version: 1.0\r\n";
        $cabecera .= "Content-type: text/html; charset = UTF-8\r\n";
        $cabecera .= "From: ".$email."\r\n";

        /* Enviamos el correo guardando su estado. */
        $enviado = mail($destinatario, $asunto, $contenido, $cabecera);
    }       

    /* Mostramos información al usuario y redireccionamos. */
    if($enviado){
        echo  '<script language="javascript">
                    window.onload = function() {
                        alert("enviado");
                    }
                </script>';
    }else{
        echo  '<script language="javascript">
                    window.onload = function() {
                        alert("noEnviado");
                    }
                </script>';
    }
?>

3: The user sees the answer below the form, which is where the previously mentioned div is. If the email was sent correctly, the form is restarted, if not, then the data is left, so that it corrects them.

As you can see, what I have tried is to show a pop using javaScript ... but I do not think the truth is nice ... so I ask ... I suppose it could be, but I do not know how ... I do not know much about php.

Surely there is some function or something similar that is not just "echo".

Programmers of PHP I acclaim you! xD (Thank you very much from Ante Mano).

    
asked by ferpaxecosanxez 26.10.2016 в 10:31
source

2 answers

0

Well, I managed to solve it, thanks to the comment of @Jose Javier Segura, I was able to find the information I needed, total, I used AJAX.

In the html code I have only removed one attribute from the form tag, so I have left now:

<form id="formulario" method="POST">                    

And the function or method I use is JQuery with Ajax such that:

function cargaRespuestaCorreo(){
    var pathFichSenMail = 'php/sendEmail.php';
    $('#botonEnviar').click(function(){
        $.ajax({
            type: "post",
            url: pathFichSenMail,
            data: $('#formulario').serialize(),
            success: function(data){
                $('#respuestaCorreo').html(data);
            }
        });
        // Evitar que se ejecute el submit del botón.
        return false;
    });
};

and the php part, I have only modified the ending, that is, the if conditional, such that:

/* Mostramos información al usuario y redireccionamos. */
if($enviado){
    echo "<p>El correo se ha enviado de forma correcta.</p>";
}else{
    echo "<p>El correo no se ha enviado.</p>";
}
    
answered by 26.10.2016 / 12:47
source
0

When you do this:

header('Location: ../contacto.html');
echo  '<script language="javascript">
           window.onload = function() {
               cargaRespuestaCorreo("enviado");
           }
        </script>';

Actually you are telling the browser to redirect to the indicated url and also display the contents of echo ... but in the current location (before performing the redirection) Since the redirection is executed upon completion the script.

Ideally, the contact page should be a php script as well, and it will be easier for you to deal with parameters via GET. In this case, you would perform the redirection to

 header('Location: ../contacto.php?send=1');

or

header('Location: ../contacto.php?send=0');

Depending on whether the submission was made (or not)

However, you can use GET parameters and treat it with javascript, although it is somewhat more complicated.

    
answered by 26.10.2016 в 10:45