PHP在联系表单上的特定DIV中回显

时间:2016-07-04 19:05:13

标签: javascript php html twitter-bootstrap

我正在使用带有验证的Bootstrap联系表单,问题是我无法在特定DIV上显示PHP echo响应,在发送表单后,浏览器会加载带有响应的contact.php文件。有没有办法在同一个HTML上显示#success_message DIV的响应?这是我的HTML:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Bootstrap 3 Contact form with Validation</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css'>
    <link rel='stylesheet prefetch' href='http://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css'>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    <div class="container">
        <form class="well form-horizontal" action="php/contacto.php" method="post"  id="contact_form">
            <fieldset>
                <div class="form-group">
                    <label class="col-md-4 control-label">Tu nombre</label>  
                    <div class="col-md-4 inputGroupContainer">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input  name="first_name" placeholder="¿Como te llamas?" class="form-control"  type="text">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-4 control-label" >Tu apellido</label> 
                    <div class="col-md-4 inputGroupContainer">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input name="last_name" placeholder="Tu apellido" class="form-control"  type="text">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-4 control-label">E-Mail</label>  
                    <div class="col-md-4 inputGroupContainer">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                            <input name="email" placeholder="tucorreo@mail.com" class="form-control"  type="text">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-4 control-label">Teléfono</label>  
                    <div class="col-md-4 inputGroupContainer">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
                            <input name="phone" placeholder="(55)1234-5678" class="form-control" type="text">
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-4 control-label">Tu comentario</label>
                    <div class="col-md-4 inputGroupContainer">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                            <textarea rows="4" class="form-control" name="comment" placeholder="¡Cuéntanos como podemos ayudarte!"></textarea>
                        </div>
                    </div>
                </div>

                <!-- Success message -->
                <div class="alert alert-success" role="alert" id="success_message">¡Listo!<i class="glyphicon glyphicon-thumbs-up"></i> Tu mensaje fue enviado, en breve nos pondremos en contacto contigo.</div>

                <!-- Button -->
                <div class="form-group">
                    <label class="col-md-4 control-label"></label>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-warning" >Enviar <span class="glyphicon glyphicon-send"></span></button>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.4.5/js/bootstrapvalidator.min.js'></script>

    <script src="js/index.js"></script>
</body>

这是我的JS:

  $(document).ready(function() {
$('#contact_form').bootstrapValidator({
    // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        first_name: {
            validators: {
                    stringLength: {
                    min: 2,
                },
                    notEmpty: {
                    message: '¡Queremos saber tu nombre!'
                }
            }
        },
         last_name: {
            validators: {
                 stringLength: {
                    min: 2,
                },
                notEmpty: {
                    message: 'Por favor, dinos tu apellido'
                }
            }
        },
        email: {
            validators: {
                notEmpty: {
                    message: 'Necesitamos una dirección de correo donde contactarte'
                },
                emailAddress: {
                    message: 'Tu dirección de correo no es válida'
                }
            }
        },
        phone: {
            validators: {
                notEmpty: {
                    message: 'Por favor, proporcionanos tu teléfono'
                },
                phone: {
                    country: 'MX',
                    message: 'Incluye un número de teléfono válido de 10 dígitos'
                }
            }
        },

        comment: {
            validators: {
                  stringLength: {
                    min: 10,
                    max: 200,
                    message:'Please enter at least 10 characters and no more than 200'
                },
                notEmpty: {
                    message: 'Please supply a description of your project'
                }
                }
            }
        }
    })
    .on('success.form.bv', function(e) {
        $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
            $('#contact_form').data('bootstrapValidator').resetForm();

        // Prevent form submission
        e.preventDefault();

        // Get the form instance
        var $form = $(e.target);

        // Get the BootstrapValidator instance
        var bv = $form.data('bootstrapValidator');

        // Use Ajax to submit form data
        $.post($form.attr('action'), $form.serialize(), function(result) {
            console.log(result);
        }, 'json');
    });
});

我的PHP:

$EmailFrom = "contacto@tuka.mx";
$EmailTo = "manuel@tuka.mx";
$Subject = "Nuevo comentario en el website";
$first_name = Trim(stripslashes($_POST['first_name'])); 
$last_name = Trim(stripslashes($_POST['last_name'])); 
$email = Trim(stripslashes($_POST['email'])); 
$phone = Trim(stripslashes($_POST['phone'])); 
$comment = Trim(stripslashes($_POST['comment'])); 

// prepare email body text
$Body = "";
$Body .= "Nombre: ";
$Body .= $first_name;
$Body .= "\n";
$Body .= "Apellido: ";
$Body .= $last_name;
$Body .= "\n";
$Body .= "E-mail: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Teléfono: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Comentario: ";
$Body .= $comment;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
    echo "<h2>¡Gracias! Recibimos tu mensaje</h2>";
}
else{
    echo "<h2>Lo sentimos, hubo un error, inténtalo nuevamente</h2>";
}
?>

我已经在这里上传了它,如果你想看到它的工作:

http://tuka.mx/beta/contacto/index.html

2 个答案:

答案 0 :(得分:0)

.on()方法的第一个参数必须是event。

下面

.on('success.form.bv', function(e) {

必须:

.on('submit', function(e) {

答案 1 :(得分:0)

看起来JS出了什么问题,这是一个解决方案:

  $(document).ready(function() {
$('#contact_form').bootstrapValidator({
    // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    submitHandler: function(validator, form, submitButton) {
    $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
            $('#contact_form').data('bootstrapValidator').resetForm();

        var bv = form.data('bootstrapValidator');
        // Use Ajax to submit form data
        $.post(form.attr('action'), form.serialize(), function(result) {
            console.log(result);
        }, 'json');
  },

    fields: {
        first_name: {
            validators: {
                    stringLength: {
                    min: 2,
                },
                    notEmpty: {
                    message: '¡Queremos saber tu nombre!'
                }
            }
        },
         last_name: {
            validators: {
                 stringLength: {
                    min: 2,
                },
                notEmpty: {
                    message: 'Por favor, dinos tu apellido'
                }
            }
        },
        email: {
            validators: {
                notEmpty: {
                    message: 'Necesitamos una dirección de correo donde contactarte'
                },
                emailAddress: {
                    message: 'Tu dirección de correo no es válida'
                }
            }
        },
        phone: {
            validators: {
                notEmpty: {
                    message: 'Por favor, proporcionanos tu teléfono'
                },
                phone: {
                    country: 'MX',
                    message: 'Incluye un número de teléfono válido de 10 dígitos'
                }
            }
        },

        comment: {
            validators: {
                  stringLength: {
                    min: 10,
                    max: 200,
                    message:'Please enter at least 10 characters and no more than 200'
                },
                notEmpty: {
                    message: 'Please supply a description of your project'
                }
                }
            }
        }
    })
});