简体   繁体   English

使用AJAX在模式下使用PHP发送电子邮件

[英]Sending email with PHP on a modal with AJAX

I have a modal that contains a form that sends email using PHP. 我有一个模式,其中包含使用PHP发送电子邮件的表单。 I do not want that Modal to close when the email is sent so I have tried to use AJAX to send it without refreshing the page. 我不希望在发送电子邮件时关闭该模式,所以我尝试使用AJAX发送而不刷新页面。 However, I cannot keep it from closing when I push submit and cannot figure out what the problem is. 但是,当我推送提交时,我无法阻止它关闭,也无法找出问题所在。 The emails still send so I believe it has something to do with 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>

The PHP 的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 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>

I have also tried this but it too closed the modal 我也尝试过这个,但是它也关闭了模态

  <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>    

Instead of calling 而不是打电话

e.preventDefault();

in the first version of your javascript just do the following: 在您的javascript的第一个版本中,只需执行以下操作:

return false;

You can also use the second version of your html and instead of calling event.preventDefault(); 您还可以使用HTML的第二版本,而不是调用event.preventDefault();。 , return false at the end of the function after the ajax call. ,在ajax调用后在函数末尾返回false。

Your second Javascript example is closer to the right answer. 您的第二个Javascript示例更接近正确答案。

You're attaching the submit event to the button id rather than the form ID, which is incorrect. 您将Submit事件附加到按钮ID而不是表单ID,这是不正确的。 You're also querying your input attributes needlessly. 您也不需要查询输入属性。 Modify your markup with something like this: 使用以下内容修改您的标记:

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

Then modify your Javascript with something like this: 然后使用以下内容修改您的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");
            }   
        });
    });
});

You also have a lot wrong with your PHP, as it would never fire due to the absence of a "submit" field from your original AJAX POST request. 您的PHP也有很多错误,因为由于原始AJAX POST请求中缺少“提交”字段,因此它永远不会触发。 Additionally, you're trying to set fields as session data, never using them in the script, and then you're unsetting them on success. 此外,您尝试将字段设置为会话数据,不要在脚本中使用它们,然后在成功时将其取消设置。

Session data is intended to persist data between requests. 会话数据旨在在请求之间保留数据。 You aren't doing that here. 你不是在这里

Secondly, even if you output an error message (which your AJAX method won't see, because you're not outputting anything), the status code returned by the request will be 200 and the success message will fire every time, even with malformed data. 其次,即使您输出错误消息(由于您未输出任何内容,您的AJAX方法也不会看到该错误消息),请求返回的状态代码仍为200,即使格式错误,每次也会触发成功消息数据。

This should be closer to what you want: 这应该更接近您想要的:

<?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);
    }
}
?>

With all of that said, this is largely untested and isn't guaranteed to work perfectly. 综上所述,这在很大程度上未经测试,不能保证完美运行。 Instead, this should give you a little bit of a better idea in terms of how everything works together. 取而代之的是,这将使您在所有事情如何协同工作方面有一个更好的主意。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM