获取else语句并将其添加到AJAX调用函数(响应)

时间:2015-07-19 09:55:48

标签: javascript php ajax

我有以下代码,除了一件小事以外,效果很好。如果输入了无效的电子邮件,那么php的else语句会出现在响应中,而我当前的响应样式类似乎已被批准。

所以,我想知道是否有任何地方我可以用我当前的代码创建一个else语句并从php中提取else响应。如果是这样,我怎么能这样做?

 <div id="contactMessageStatus"></div>
    <div class="contactForm">
        <form action="" method="post" id="mycontactform" >
            <input type="text" class="inputbar" name="name" placeholder="Full Name" required>
            <input type="email" class="inputbaremail" name="email" placeholder="Email" required>
            <textarea rows="4" cols="50" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
            <input type="button" class="contactButton" value="Send Message" id="submit">
        </form>
    </div>

AJAX

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

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

    $.post("contactSend.php", $("#mycontactform").serialize(),  function(response) {
    $('#contactMessageStatus').append(response);
    $('#contactMessageStatus').addClass("contactSuccess");
    $('html, body').animate({
        scrollTop: $("#contactMessageStatus").offset().top
     }, 2000);
    $('#contactMessageStatus').html(response);
    $('#contactMessageStatus').delay(5500).fadeOut(400);
    });
    return false;
    });
    });
</script>

用于显示回显响应的PHP文件:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = 'contact@example.com';
$subject = 'SFL Contact Form Submitted';
$message = 'FROM: '.$name. ' ' . ' Email: '.$email. ' ' . 'Message: '.$message;
$headers = 'From: contact@example.com' . "\r\n";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{
echo "Invalid Email, please provide an correct email.";
}
?>

1 个答案:

答案 0 :(得分:1)

基于有问题的评论:

$(document).ready(function(){

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

        $.post("contactSend.php", $("#mycontactform").serialize(),  function(response) {
            if (response == 'Your email was sent!') {
                $('#contactMessageStatus').append(response);
                $('#contactMessageStatus').addClass("contactSuccess");
                $('html, body').animate({
                    scrollTop: $("#contactMessageStatus").offset().top
                 }, 2000);
                $('#contactMessageStatus').html(response);
                $('#contactMessageStatus').delay(5500).fadeOut(400);
            }
            else {
                // whatever error handling you want goes here
            }
        });
        return false;
    });
});