简体   繁体   中英

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({
        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:

<?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({
        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 . Make sure you are using .val() or .value . You are probably using .text() on all of the form fields and it is failing for your 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
    $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 . You are duplicating your efforts on adding it again. You will want to edit that block...or remove it and build out the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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