AJAX表单提交疑难解答

时间:2016-04-20 11:48:02

标签: javascript php jquery ajax forms

此刻我正在摸着这个 - 如果你们中的任何一个人能够帮助那就太棒了。我有一个网站使用AJAX在简单验证后提交联系表格。一切顺利,网站就像电子邮件发送一样,但我没有收到任何电子邮件(是的,我已经三次检查,这是正确的电子邮件地址)。

以下是我正在使用的内容:

HTML / PHP

<script type="text/javascript" language="javascript" src="js/contact.js"></script>

...

<section id="contact">

<span class="contact_results"></span>

<div class="form">
    <input type="text" name="name" id="contactname" required value="<? echo $user_name ?>" placeholder="Your Name:" autocomplete="off">
    <input type="email" name="email" id="email" required value="<? echo $email ?>" placeholder="Your E-Mail Address:" autocomplete="off">
    <input type="phone" name="phone" id="phone" value="<? echo $phone ?>" placeholder="Your Telephone Number:" autocomplete="off">
    <textarea name="message" id="message" required placeholder="Your Message:"><? echo $message ?></textarea>
    <button type="submit" name="submit" id="contactbutton">Submit Form</button>
</div>

</section>

Contact.js

$(function() {

    $("#contact button").click(function() {

        var proceed = true;
        //simple validation at client's end
        //loop through each field and we simply change border color to red for invalid fields       
        $("#contact input[required=true], #contact textarea[required=true]").each(function(){
            $(this).css('border-color','#EEE'); 
            if(!$.trim($(this).val())){ //if this field is empty 
                $(this).css('border-color','#FC0'); //change border color to red   
                proceed = false; //set do not proceed flag
            }
            //check invalid email
            var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
            if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
                $(this).css('border-color','#FC0'); //change border color to red   
                proceed = false; //set do not proceed flag              
            }   
        });

        if(proceed) //everything looks good! proceed...
        {

            //get input field values data to be sent to server
            post_data = {
                'user_name'     : $('input[name=name]').val(), 
                'user_email'    : $('input[name=email]').val(), 
                'user_phone'    : $('input[name=phone]').val(),  
                'msg'           : $('textarea[name=message]').val()
            };

            //Ajax post data to server
            $.post('contact_sendform.php', post_data, function(response){  
                if(response.type == 'error'){ //load json data from server and output message     
                    output = '<span class="error">'+response.text+'</span>';
                }else{
                    output = '<span class="success">'+response.text+'</span>';
                    //reset values in all input fields
                    $("#contact  input[required=true], #contact textarea[required=true]").val(''); 
                    $(".form").fadeOut(400); //hide form after success
                }
                $("#contact .contact_results").hide().html(output).slideDown(400);
            }, 'json');
        }
    });

    //reset previously set border colors and hide all message on .keyup()
    $("#contact  input[required=true], #contact textarea[required=true]").keyup(function() { 
        $(this).css('border-color',''); 
        $("#result").slideUp();
    });
});

contact_sendform.php

<?php
if($_POST)
{
$to_email       = "xxxxxxxx@hotmail.com";

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    $output = json_encode(array(            //create JSON data
        'type'=>'error', 
        'text' => 'Sorry Request must be Ajax POST'
    ));
    die($output); //exit script outputting json data
} 

//Sanitize input data using PHP filter_var().
$user_name      = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_email     = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$user_phone     = filter_var($_POST["user_phone"], FILTER_SANITIZE_NUMBER_INT);
$message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

//additional php validation
if(strlen($user_name)<3){ // If length is less than 4 it will output JSON error.
    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
    die($output);
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if(strlen($message)<3){ //check emtpy message
    $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
    die($output);
}

//email body
$message_body = $message."\r\n\r\n-".$user_name."\r\nEmail : ".$user_email."\r\nPhone Number : ". $user_phone ;

// Set Subject
$subject = "Ian! You've got a new message from ".$user_name;

//proceed with PHP email.
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$headers .= 'From: '.$user_email."\r\n".
'Reply-To: '.$user_email."\r\n" .
'X-Mailer: PHP/' . phpversion();

$send_mail = mail($to_email, $subject, $message_body, $headers);

if(!$send_mail)
{
    //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
    $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
    die($output);
}else{
    $userArray = explode(' ', trim($user_name));
    $output = json_encode(array('type'=>'message', 'text' => 'Thanks for getting in touch, '.$userArray[0] .'!'));
    die($output);
}
}
?>

正如我所说 - 当表单提交正确的数据时,它会显示确认消息,该消息仅在$ sendMail工作时触发 - 所以我不知道出了什么问题。任何见解或帮助都将受到重视 - 谢谢! :)

0 个答案:

没有答案