简体   繁体   English

Ajax 联系表单脚本不会在电子邮件中发送消息

[英]Ajax Contact Form Script Doesn't Send the Message in the Email

So I have written a script in ajax that connects to a PHP mail() script to send an email to info@example.com (obviously replacing example.com with my domain) and the email sends fine, everything is setup except for one problem:所以我在 ajax 中编写了一个脚本,该脚本连接到 PHP mail() 脚本以向info@example.com发送电子邮件(显然用我的域替换了 example.com)并且电子邮件发送正常,除了一个问题外,一切都设置好了:

     $.ajax({
        url:'contact.php',
        type:'POST',
        data: {
           name:name,
           email:email,
           message:message
          },
        dataType: 'json',
        success: function(response){
            alert(response);
        },
        error: function(response){
            alert("Oops, something went wrong. Please try again.");
        }
    })
    return false;
    event.preventDefault();
    })

The email I receive is formatted exactly as my contact.php states:我收到的电子邮件的格式与我的 contact.php 声明的完全一样:

<?php
    $to = "info@example.com";
    $from = $_POST['email'];
    $name = $_POST['name'];
    $message =$_POST['message'];
    echo $_POST['test'];
    $subject = "Contact form from: ".$name;
    $body = 'Hello developer(s)!<br><br>
The following is a submission from the Contact Form on <a target="_blank" href="https://example.com">example.com</a>. Please respond using your own email (like info@example.com).<br><br>
Name: '.$name."<br>
Email: ".$from."<br>
Message: <br>".$message."<br><br>
Thank you!";
    $headers = "From: ".$name." <".$from."> \r\n";
    $headers .= 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    mail($to,$subject,$body,$headers);
    echo "Success!<br></br>";
?>

Which outputs the following:输出以下内容:

Hello developer(s)!

The following is a submission from the Contact Form on example.com. Please respond using your own email (like info@example.com).

Name: Owen Sullivan
Email: sulliops@gmail.com
Message: 


Thank you!

Notice that the message is missing, even though a message has been submitted in the form.请注意,即使已在表单中提交了一条消息,该消息也丢失了。 Any idea why this is the only part missing?知道为什么这是唯一缺少的部分吗?

EDIT: This is the form code:编辑:这是表单代码:

<form method="post" name="cform" id="cform" action="contact.php" class="contact-form">
    <div class="row">
        <div class="col-sm-6">
            <input name="name" id="name" type="text" class="form-control" placeholder="Your Name..." required>
        </div>
        <div class="col-sm-6">
            <input name="email" id="email" type="email" class="form-control" placeholder="Your Email..." required>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-12">
            <textarea name="message" id="message" cols="" rows="4" class="form-control" placeholder="Your Message..." required></textarea>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12 text-right">
            <input type="submit" id="submit" name="send" class="submitBnt btn btn-custom" value="Send Message">
        </div>
    </div>
    <div id="simple-msg"></div>
</form>

FIXED AJAX CODE:固定的 AJAX 代码:

$.ajax({
        url:'contact.php',
        type:'POST',
        data: $(this).serialize()
        dataType: 'json',
        success: function(response){
            alert(response);
        },
        error: function(response){
            alert("Oops, something went wrong. Please try again.");
        }
    })
    return false;
    event.preventDefault();
    })

You need to check where you are getting the value for the "message" textarea .您需要检查从何处获取“消息” textarea的值。 Make sure you are using .val() or .value .确保您使用的是.val().value You are probably using .text() on all of the form fields and it is failing for your textarea .您可能在所有表单字段上使用.text()并且它对您的textarea失败。

Here are some changes I would suggest以下是我建议的一些更改

// You have a syntax error on yours, you need a listener
$(document).ready(function() {
    /** Listen for submit **/
    $("#cform").on("submit",function(event) {
        // Stop form from submitting normally
        event.preventDefault();
        // Send ajax
        $.ajax({
            url: 'contact.php',
            type: 'POST',
            // Serialize the form
            data: $(this).serialize(),
            // Remove the json
            success: function(response){
                alert(response);
            },
            error: function(response){
                alert("Oops, something went wrong. Please try again.");
            }
        });
    });
});

Then in your PHP would be something like:然后在你的 PHP 中会是这样的:

    <?php
    $to      = "info@example.com";
    $from    = trim($_POST['email']);
    # Stop if you don't have a valid address
    if(!filter_var($from,FILTER_VALIDATED_EMAIL))
        die('Invalid email address.');
    # Strip out stuff from the submission
    $name    = htmlspecialchars(strip_tags(trim($_POST['name'])));
    $message = htmlspecialchars(strip_tags(trim($_POST['message'])));

    $subject = "Contact form from: ".$name;
    $body    = 'Hello developer(s)!<br /><br />
The following is a submission from the Contact Form on <a target="_blank" href="https://example.com">example.com</a>. Please respond using your own email (like info@example.com).<br><br>
Name: '.$name."<br>
Email: ".$from."<br>
Message: <br />".$message."<br /><br />
Thank you!";
    $headers = "From: ".$name." <".$from."> \r\n";
    $headers .= 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    # You need to make a condition to make sure it does, in fact, send
    echo (mail($to,$subject,wordwrap($body, 70, "\r\n"),$headers))? 'Success!' : 'Failed to send message.';


EDIT:编辑:

NOTE: You have two submissions for ajax, the one you are adding and the one in your <script src="js/app.js"></script> file starting at line 76 .注意:您有两个 ajax 提交,一个是您要添加的,另一个是在<script src="js/app.js"></script>文件中从第76行开始的。 You are duplicating your efforts on adding it again.您正在重复添加它的工作。 You will want to edit that block...or remove it and build out the above.您将要编辑该块...或将其删除并构建上述内容。

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

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