javascript - 发送电子邮件表格并在同一页面上继续

标签 javascript php jquery ajax email

我可以发送电子邮件并正常接收,但想单击提交按钮,表单已发送并向用户显示一条消息并正常继续在页面上... Ja 尝试了 ajax 和所有内容,但什么也没有。

我希望消息出现在 div 中,与下图相同。

html

<form class="well form-horizontal" action="php/contato.php" method="post" id="contact_form">
    <fieldset>

            <legend style="text-align: center;">Fale conosco</legend>

        <!-- Nome -->

        <div class="form-group">
            <label class="col-md-4 control-label">Nome</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="name" placeholder="Nome Completo" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- Email-->
        <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="E-Mail" class="form-control" type="text" required>
                </div>
            </div>
        </div>


        <!-- Telefone-->

        <div class="form-group">
            <label class="col-md-4 control-label">Telefones</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="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br>
                    <input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text">
                </div>
            </div>
        </div>

        <!-- Assunto-->

        <div class="form-group">
            <label class="col-md-4 control-label">Assunto</label>
            <div class="col-md-4 inputGroupContainer">
                <div class="input-group">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span>
                    <input name="assunto" placeholder="Assunto" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- Mensagem -->

        <div class="form-group">
            <label class="col-md-4 control-label">Deixe-nos sua mensagem.</label>
            <div class="col-md-6 inputGroupContainer">
                <div class="input-group">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                    <textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea>
                </div>
            </div>
        </div>

        **<!-- I want the message to appear here -->**
        <div class="alert alert-success" role="alert" id="success_message">Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.</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>

JavaScript

   $(function () {

    $('#contact_form').validator();

    $('#contact_form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "php/contato.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact_form').find('.messages').html(alertBox);
                        $('#contact_form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
}); 

contato.php

    <?php

// configure
$from = 'email';
$sendTo = 'email';
$subject = 'Contato do site';
$fields = array('name' => 'Nome do Cliente', 'email' => 'Email', 'telefone' => 'Telefone', 'celular' => 'Celular', 'assunto' => 'Assunto', 'mensagem' => 'Mensagem'); // array variable name => Text to appear in email
$okMessage = 'Email enviado, já já entraremos em contato';
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor';

// let's do the sending

try
{
    $emailText = "Mais um contato chegando através do site\n=============================\n";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    mail($sendTo, $subject, $emailText, "From: " . $from);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
 ?>

send email

最佳答案

...
$('#contact_form').on('submit', function (e) {
    if (!e.isDefaultPrevented()) {
...

您没有阻止默认操作。

您可能想使用:

...
$('#contact_form').on('submit', function (e) {
    // Prevent form submission
    e.preventDefault();
    if (true) { // you no longer need the if-block
...

关于javascript - 发送电子邮件表格并在同一页面上继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37514229/

相关文章:

php - 为什么我的 WordPress functions.php 无法加载样式或脚本?

php - Laravel 构造函数重定向不起作用

javascript - 检测键盘箭头键按下了多长时间?

javascript - 哪个 HTML 元素的事件是 asp :RegularExpressionValidator client side validation bound?

javascript - 如何防止多次单击/点击的默认处理?

javascript - React.js onMouseOver 中的两个函数

php - 从javascript调用php文件

php - 静态网页 vs MySql 生成

javascript - HTML/jQuery : Make div disappear and use Canvas underneath

javascript - html5 canvas删除垂直/水平线像素值