Ajax jQuery Html Email Form Output on Same Page

时间:2017-04-10 02:31:09

标签: jquery html ajax forms contact

I want the PHP message to output on the page instead of going to the PHP on a new screen. Here's my codes.

PHP

<?php
// VALUES FROM THE FORM
$name    = $_POST['name'];
$email   = $_POST['email'];
$subject = $_POST["subject"];
$message = $_POST['message'];

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        print "Oops! There was a problem with your submission. Please complete the form and try again.";
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    // CREATE THE EMAIL
    $headers    = "Content-Type: text/plain; charset=iso-8859-1\n";
    $headers   .= "From: $name <$email>\r\n";
    $recipient  = "myemail@outlook.com";
    $subject    = "Message to Me - $subject";
    $message    = wordwrap($message, 1024);

    // Send the email.
    if (mail($recipient, $subject, $message, $headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        print "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        print "Oops! Something went wrong and we couldn't send your message.";
    }
} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    print "There was a problem with your submission, please try again.";
}

HTML

<form id="form_contact" class="submit-form" method="post" action="process.php">

    <!--Name and Email Field Box-->
    <div class="row">
        <div class="col-sm-6 addpadding">
          <div class="box text-input">
                <input id="name" type="text" name="name" required />
            <label>Your Name</label>
          </div>
        </div>
        <div class="col-sm-6 addpadding">
            <div class="box text-input">
                <input id="email" type="text" name="email" required />
                <label>Your email</label>
                <span></span>
            </div>
        </div>
    </div>

    <!--Subject Field Box-->
    <div class="box text-input">
        <input id="subject" type="text" name="subject" required />
        <label>Your subject</label>
        <span></span>
    </div>

    <!--Message Field Box-->
    <div class="box text-input textarea">
        <textarea id="message" name="message" required></textarea>
        <label>Your message</label>
        <span></span>
    </div>

    <!--Submit Button-->
    <div class="button raised purple">
        <input id="submit_message" type="submit" value="Send Your Message"/>
    </div>

    <span class="loading"><i class="fa fa-spinner fa-pulse"></i></span>

    <div class="clearfix"></div>

    <div id="reply_message"></div>

</form>

JS

$("#submit_message").on("click", function() {
$('#reply_message').removeClass();
$('#reply_message').html('')
var regEx = "";

// validate Name
var name = $("input#name").val();
regEx=/^[A-Za-z .'-]+$/;
if (name == "" || name == "Name"  || !regEx.test(name)) {
    $("input#name").val('');
    $("input#name").focus();
    return false;
}

// validate Email
var email = $("input#email").val();
regEx=/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
if (email == "" || email == "Email" || !regEx.test(email)) {
    $("input#email").val('');
    $("input#email").focus();
    return false;
}

// validate Subject
var subject = $("input#subject").val();
regEx=/^[A-Za-z0-9 .'-]+$/;
if (subject == "" || subject == "subject"  || !regEx.test(subject)) {
    $("input#subject").val('');
    $("input#subject").focus();
    return false;
}

// validate Message
var mymessage = $("textarea#mymessage").val();
if (mymessage == "" || mymessage == "message" || mymessage.length < 2) {
    $("textarea#message").val('');
    $("textarea#message").focus();
    return false;
}
    return valid;

var dataString = 'name='+ $("input#name").val() + '&email=' + $("input#email").val() + '&subject='+ $("input#subject").val() + '&mymessage=' + $("textarea#mymessage").val();

$('.loading').fadeIn(500);

// Send form data to mailer.php
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    success: function() {
        $('.loading').hide();
        $('#reply_message').addClass('list3');
        $('#reply_message').html("<span>Mail sent successfully</span>")
        .hide()
        .fadeIn(1500);
        $('#form_contact')[0].reset();
        }
    });

Thanks in advance.

1 个答案:

答案 0 :(得分:0)

1st. your last code block is not complete it's missing }

2nd. if you are using Ajax you should stop click event propagation

3rd. if submit button type is submit and you are using Ajax you should return false eventually

$("#submit_message").on("click3rd", function(e) {
    // stop event propagation
    // if you are return false eventually this would not necessary
    e.stopPropagation()

    $('#reply_message').removeClass();
    $('#reply_message').html('')
    var regEx = "";

    // validate Name
    var name = $("input#name").val();
    regEx = /^[A-Za-z .'-]+$/;
    if (name == "" || name == "Name" || !regEx.test(name)) {
        $("input#name").val('');
        $("input#name").focus();
        return false;
    }

    // validate Email
    var email = $("input#email").val();
    regEx = /^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
    if (email == "" || email == "Email" || !regEx.test(email)) {
        $("input#email").val('');
        $("input#email").focus();
        return false;
    }

    // validate Subject
    var subject = $("input#subject").val();
    regEx = /^[A-Za-z0-9 .'-]+$/;
    if (subject == "" || subject == "subject" || !regEx.test(subject)) {
        $("input#subject").val('');
        $("input#subject").focus();
        return false;
    }

    // validate Message
    var mymessage = $("textarea#mymessage").val();
    if (mymessage == "" || mymessage == "message" || mymessage.length < 2) {
        $("textarea#message").val('');
        $("textarea#message").focus();
        return false;
    }

    var dataString = 'name=' + $("input#name").val() + '&email=' + $("input#email").val() + '&subject=' + $("input#subject").val() + '&mymessage=' + $("textarea#mymessage").val();

    $('.loading').fadeIn(500);

    // Send form data to mailer.php
    $.ajax({
        type: "POST",
        url: "process.php",
        data: dataString,
        success: function () {
            $('.loading').hide();
            $('#reply_message').addClass('list3');
            $('#reply_message').html("<span>Mail sent successfully</span>")
                .hide()
                .fadeIn(1500);
            $('#form_contact')[0].reset();
        }
    });

    // return false to stop form submit, because you are using ajax already
    return false
}