change browser response when sending mail via php

0

at the time of pressing send in the form of my page redirect me to contact_me.php as I can make it on the same page index.html

form:

<form name= "sentMessage" " method="post" action="contact_me.php">
 <div class="row">
 <div class="col-md-6">
 <div class="form-group">
 <input type="text" class="form-control" name="name" placeholder="Nombre *" id="name" required data-validation-required-message="Please enter your name.">
     <p class="help-block text-danger"></p>
      </div>
     <div class="form-group">
  <input type="email" class="form-control" name="email" placeholder="E-mail *" id="email" required data-validation-required-message="Please enter your email address.">
  <p class="help-block text-danger"></p>
      </div>
  <div class="form-group">
  <input type="tel" class="form-control" name="phone" placeholder="Telefono *" id="phone" required data-validation-required-message="Please enter your phone number.">
   <p class="help-block text-danger"></p>
                               </div>
                            </div>
                          <div class="col-md-6">
                                <div class="form-group">
  <textarea class="form-control"name="message" placeholder="Mensaje *"  id="message" required data-validation-required-message="Please enter a message."></textarea>
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            <div class="col-lg-12 text-center">
                                <div id="success"></div>
                              <button type="submit" class="btn btn-primary">enviar mensaje</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

my php is the next one

<?php

if(!empty($_POST['name'])        &&
   !empty($_POST['email'])       &&
   !empty($_POST['phone'])       &&
   !empty($_POST['message'])     &&
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {

   // Enviar mail
}
$name = $_POST['name'];
$email_address= $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            



?>
    
asked by Hector 12.11.2016 в 04:34
source

2 answers

0

For that use ajax, the following example can serve you ... If your answer to the page returns true you can show a div that in its normal state is hidden ... and then you show it in your answer "true" in case otherwise you can put an error. I also recommend that before sending your form you validate it.

 $(document).ready( function() {   // Esta parte del código se ejecutará automáticamente cuando la página esté lista.
            $("#btn").submit( function() {     // Con esto establecemos la acción por defecto de nuestro botón de enviar.
                //if(validaForm()){                               // Primero validará el formulario.
                    $.post("contact_me.php",$("form[name='sentMessage']").serialize(),function(res){
                        $("form[name='sentMessage']").fadeOut("slow");   // Hacemos desaparecer el div "formulario" con un efecto fadeOut lento.
                        if(res){
                            $("#exito").delay(500).fadeIn("slow");      // Si hemos tenido éxito, hacemos aparecer el div "exito" con un efecto fadeIn lento tras un delay de 0,5 segundos.
                        } else {
                            $("#fracaso").delay(500).fadeIn("slow");    // Si no, lo mismo, pero haremos aparecer el div "fracaso"
                        }
                    });
               // } // fin de la validacion
            });    
        });

The complete example can be reviewed from the following link

    
answered by 12.11.2016 / 05:52
source
1

in the end I could solve it, thanks to the help of cig, implement ajax from 0 I leave the solution: My index of the form is as follows:

    <!DOCTYPE HTML>
<html
<head>
    <title>Formulario de Contacto</title>
    <link rel="stylesheet" href="estilos.css" />
</head>
<body>
    <form method="post" class="contacto">
        <fieldset>
            <div><label>Nombre:</label><input type="text" class="nombre" name="nombre" /></div>
            <div><label>Email:</label><input type="text" class="email" name="email" /></div>
            <div><label>Telefono:</label><input type="text" class="telefono" name="email" /></div>
            <div><label>Mensaje:</label><textarea cols="30" rows="5" class="mensaje" name="mensaje" ></textarea></div>
            <div class="ultimo">
                <img src="ajax.gif" class="ajaxgif hide" />
                <div class="msg"></div>
                <button class="boton_envio">Enviar Mensaje</button>
            </div>
        </fieldset>
     </form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="funciones.js"></script>
</body>
</html>

my php:

<?php
// Guardar los datos recibidos en variables:
$nombre = $_POST['nombre'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$mensaje = $_POST['mensaje'];
// Definir el correo de destino:
$dest = "[email protected]"; 

// Estas son cabeceras que se usan para evitar que el correo llegue a SPAM:
$headers = "From: $nombre <$email>\r\n";  
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Aqui definimos el asunto y armamos el cuerpo del mensaje
$asunto = "Contacto";
$cuerpo = "Nombre: ".$nombre."<br>";
$cuerpo .= "Email: ".$email."<br>";
$cuerpo .= "Telefono: ".$telefono."<br>";
$cuerpo .= "Mensaje: ".$mensaje;

// Esta es una pequena validación, que solo envie el correo si todas las variables tiene algo de contenido:
if($nombre != '' && $email != '' && $telefono != '' && $mensaje != ''){
    mail($dest,$asunto,$cuerpo,$headers); //ENVIAR!
}
?>

mi js:

(function(){
    $(".boton_envio").click(function() {

        var nombre = $(".nombre").val();
            email = $(".email").val();
            validacion_email = /^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/;
            telefono = $(".telefono").val();
            mensaje = $(".mensaje").val();

        if (nombre == "") {
            $(".nombre").focus();
            return false;
        }else if(email == "" || !validacion_email.test(email)){
            $(".email").focus();    
            return false;
        }else if(telefono == ""){
            $(".telefono").focus();
            return false;
        }else if(mensaje == ""){
            $(".mensaje").focus();
            return false;
        }else{
            $('.ajaxgif').removeClass('hide');
            var datos = 'nombre='+ nombre + '&email=' + email + '&telefono=' + telefono + '&mensaje=' + mensaje;
            $.ajax({
                type: "POST",
                url: "proceso.php",
                data: datos,
                success: function() {
                    $('.ajaxgif').hide();
                    $('.msg').text('Mensaje enviado!').addClass('msg_ok').animate({ 'right' : '130px' }, 300);  
                },
                error: function() {
                    $('.ajaxgif').hide();
                    $('.msg').text('Hubo un error!').addClass('msg_error').animate({ 'right' : '130px' }, 300);                 
                }
            });
            return false;
        }

    });
})();

I hope you can send someone a greeting.

    
answered by 12.11.2016 в 17:53