使用AJAX在模式上发送带有PHP的电子邮件

时间:2015-10-23 23:28:22

标签: php jquery ajax forms bootstrap-modal

我有一个模式,其中包含使用PHP发送电子邮件的表单。我不希望在发送电子邮件时关闭Modal,所以我尝试使用AJAX发送它而不刷新页面。但是,当我按下提交时,我无法阻止它关闭,并且无法弄清楚问题是什么。电子邮件仍然发送,所以我认为它与AJAX有关。

    <?php include 'email_form.php';?>

    <?php echo $result; ?>

<form method="post">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" class="form-control" placeholder="Your Name"
        value="<?php echo $_SESSION['post-data']['name']; ?>" />
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" class="form-control" placeholder="Your Email"
        value="<?php echo $_SESSION['post-data']['email']; ?>" />
    </div>
    <div class="form-group">
        <label for="comment">Comment:</label>
        <textarea class="form-control" id="comment" name="comment"><?php echo $_SESSION['post-data']['comment']; ?></textarea>
    </div>
    <div class="modal-footer text-center">
        <input type="submit" name="submit" id="submit" class="btn" value="Submit"/>
    </div>
</form>

PHP

<?php

  $_SESSION['post-data'] = $_POST;

    $name = strip_tags($_POST['name']);
    $email = strip_tags($_POST['email']);
    $comment = strip_tags($_POST['comment']);

        if ($_POST["submit"]) {



             if (!$_POST['name']) {
                $error="<br />Please enter your name";
             }

             if (!$_POST['email']) {
                $error.="<br />Please enter your email address";
             }

             if (!$_POST['comment']) {
                 $error.="<br />Please enter a comment";
            }

             if ($_POST['email']!="" AND !filter_var($_POST['email'],
                FILTER_VALIDATE_EMAIL)) {
                 $error.="<br />Please enter a valid email address";
             }

             if ($error) {
                 $result='<div class="alert alert-danger"><strong>There were error(s)
                in your form:</strong>'.$error.'</div>';

         } else {

            if (mail("user@email.com", "Comment from website.com", "Name: ".
            $_POST['name']."
                Email: ".$_POST['email']."
                Comment: ".$_POST['comment'])) 

            {
             $result='<div class="alert alert-success"><strong>Thank
            you!</strong> I\'ll be in touch.</div>';

            unset($_SESSION['post-data']['name']);
            unset($_SESSION['post-data']['email']);
            unset($_SESSION['post-data']['comment']);
            session_destroy();

         } else {
            $result='<div class="alert alert-danger">Sorry, there was
            an error sending your message. Please try again later.</div>';

        }

     }
 }

?>

的JavaScript

      <script>
$(document).ready(function () {

    $('#submit').click(function(event) {

    $('.modal').on('hide.bs.modal', function(e) {         
        e.preventDefault();
        });

    var formData = {
        'name'              : $('input[id=name]').val(),
        'email'             : $('input[id=email]').val(),
        'comment'           : $('input[id=comment]').val(),    
    };

    $.ajax({
        type: "post",
        url: "email_form.php", 
        data: formData,
        success: function(msg){
           alert("Email sent");
        },
        error: function(){
            alert("Please try to resubmit");
        }   
    });
});
});

</script>

我也尝试了这个,但它关闭了模态

  <script>
 $(document).ready(function () {

    $('#submit').submit(function(event) {

        event.preventDefault();


    var formData = {
        'name'              : $('input[id=name]').val(),
        'email'             : $('input[id=email]').val(),
        'comment'           : $('input[id=comment]').val(),    
    };

    $.ajax({
        type: "post",
        url: "email_form.php", 
        data: formData,
        success: function(msg){
           alert("Email sent");
        },
        error: function(){
            alert("Please try to resubmit");
        }   
    });
});
});

</script>    

2 个答案:

答案 0 :(得分:0)

而不是打电话

e.preventDefault();

在您的javascript的第一个版本中,只需执行以下操作:

return false;

您还可以使用html的第二个版本,而不是调用event.preventDefault(); ,在ajax调用后,在函数结束时返回false。

答案 1 :(得分:0)

您的第二个Javascript示例更接近正确答案。

您将提交事件附加到按钮ID而不是表单ID,这是不正确的。您还在不必要地查询输入属性。使用以下内容修改标记:

<form id="email-submit-form" method="post">

然后使用以下内容修改您的Javascript:

<script>
$(document).ready(function () {

    $('#email-submit-form').submit(function(event) {

        event.preventDefault();

        var formData = {
            'name'              : $('#name').val(),
            'email'             : $('#email').val(),
            'comment'           : $('#comment').val(),
            'submit'            : 'AJAX'  //Rudimentary example to help you differentiate between POST types
        };

        $.ajax({
            type: "post",
            url: "email_form.php", 
            data: formData,
            success: function(msg){
               alert(msg); //See my notes below
            },
            error: function(){
                alert("Please try to resubmit");
            }   
        });
    });
});

你的PHP也有很多错误,因为你原来的AJAX POST请求中没有“submit”字段,所以它永远不会触发。此外,您尝试将字段设置为会话数据,从不在脚本中使用它们,然后在成功时取消设置。

会话数据旨在在请求之间保留数据。你不是在这里做的。

其次,即使您输出错误消息(您的AJAX方法将看不到,因为您没有输出任何内容),请求返回的状态代码将为200,并且每次都会触发成功消息,即使数据格式错误。

这应该更接近你想要的东西:

<?php

$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$comment = strip_tags($_POST['comment']);

if ($_POST["submit"]) {
    $error = '';
    if (!$name){
        $error="<br />Please enter your name";
    }
    if (!$email) {
        $error.="<br />Please enter your email address";
    }
    if(!$comment) {
        $error.="<br />Please enter a comment";
    }
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error.="<br />Please enter a valid email address";
    }
    if ($error) {
        $result='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong>'.$error.'</div>';
    }
    else {
        if(mail("user@email.com", "Comment from website.com",
            "Name: ".$name."
            Email: ".$email."
            Comment: ".$comment)
        ){
            $result='<div class="alert alert-success"><strong>Thank you!</strong> I\'ll be in touch.</div>';
        } else {
            $result='<div class="alert alert-danger">Sorry, there was
            an error sending your message. Please try again later.</div>';    
        }
    }
    /*
    This will only fire on your above AJAX request, and stop the server from running 
    after this point. All you need is the response for your AJAX script to read
    */
    if($_POST['submit'] === 'AJAX'){
        die($result);
    }
}
?>

所有这些都说明了,这在很大程度上是未经测试的,并不能保证完美运行。相反,这应该会让你在一切如何协同工作方面有一个更好的想法。

祝你好运。