带下拉列表的Ajax联系表单选择发送电子邮件的位置

时间:2015-08-25 22:34:31

标签: php jquery html ajax contact-form

我按照本教程创建了一个联系表单:http://www.sanwebe.com/2011/12/making-simple-jquery-ajax-contact-form

该表单效果很好,但我想为用户添加一个选项,以便在下拉列表中选择一个项目,该项目将决定表单将发送到哪个电子邮件地址。我整天都在研究这个问题,但无法弄清楚如何使用这个特定的代码来实现它。

HTML:

<div class="form-style" id="contact_form">
<div class="form-style-heading">Please Contact Us</div>
<div id="contact_results"></div>
<div id="contact_body">
    <label><span>Name <span class="required">*</span></span>
        <input type="text" name="name" id="name" required="true" class="input-field"/>
    </label>
    <label><span>Email <span class="required">*</span></span>
        <input type="email" name="email" required="true" class="input-field"/>
    </label>
    <label><span>Phone</span>
        <input type="text" name="phone1" maxlength="4" placeholder="+91"  required="true" class="tel-number-field"/>&mdash;<input type="text" name="phone2" maxlength="15"  required="true" class="tel-number-field long" />
    </label>
        <label for="subject"><span>Regarding</span>
        <select name="subject" class="select-field">
        <option value="General Question">General Question</option>
        <option value="Advertise">Advertisement</option>
        <option value="Partnership">Partnership Oppertunity</option>
        </select>
    </label>
    <label for="field5"><span>Message <span class="required">*</span></span>
        <textarea name="message" id="message" class="textarea-field" required="true"></textarea>
    </label>
    <label>
        <span>&nbsp;</span><input type="submit" id="submit_btn" value="Submit" />
    </label>
</div>

脚本:

$(document).ready(function() {
$("#submit_btn").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_form input[required=true], #contact_form textarea[required=true]").each(function(){
        $(this).css('border-color',''); 
        if(!$.trim($(this).val())){ //if this field is empty 
            $(this).css('border-color','red'); //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','red'); //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(), 
            'country_code'  : $('input[name=phone1]').val(), 
            'phone_number'  : $('input[name=phone2]').val(), 
            'subject'       : $('select[name=subject]').val(), 
            'msg'           : $('textarea[name=message]').val()
        };

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

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

PHP:

<?php
if($_POST)
{
$to_email       = "myemail@gmail.com"; //Recipient email, Replace with own email here

//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);
$country_code   = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
$phone_number   = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
$subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

//additional php validation
if(strlen($user_name)<4){ // 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(!filter_var($country_code, FILTER_VALIDATE_INT)){ //check for valid numbers in country code field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in country code'));
    die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
    die($output);
}
if(strlen($subject)<3){ //check emtpy subject
    $output = json_encode(array('type'=>'error', 'text' => 'Subject is required'));
    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 : (".$country_code.") ". $phone_number ;

//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\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{
    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
    die($output);
}
}
?>

这似乎是很多人提出的问题,但我无法找到包含所有内容的解决方案 - HTML和所有内容。我是PHP的新手,但我非常确定通过添加“如果&#39;在PHP中。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

HTML

<div class="form-style" id="contact_form">
<div class="form-style-heading">Please Contact Us</div>
<div id="contact_results"></div>
<div id="contact_body">
    <label><span>Name <span class="required">*</span></span>
        <input type="text" name="name" id="name" required="true" class="input-field"/>
    </label>
    <label><span>Email <span class="required">*</span></span>
        <input type="email" name="email" required="true" class="input-field"/>
    </label>
    <label><span>Phone</span>
        <input type="text" name="phone1" maxlength="4" placeholder="+91"  required="true" class="tel-number-field"/>&mdash;<input type="text" name="phone2" maxlength="15"  required="true" class="tel-number-field long" />
    </label>            
<label for="subject"><span>Send To</span>
        <select name="sendto" class="select-field">
        <option value="email1@email.com">email1</option>
        <option value="email2@email.com">email2</option>
        </select>
    </label>
        <label for="subject"><span>Regarding</span>
        <select name="subject" class="select-field">
        <option value="General Question">General Question</option>
        <option value="Advertise">Advertisement</option>
        <option value="Partnership">Partnership Oppertunity</option>
        </select>
    </label>
    <label for="field5"><span>Message <span class="required">*</span></span>
        <textarea name="message" id="message" class="textarea-field" required="true"></textarea>
    </label>
    <label>
        <span>&nbsp;</span><input type="submit" id="submit_btn" value="Submit" />
    </label>
</div>

脚本将是

$(document).ready(function() {
$("#submit_btn").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_form input[required=true], #contact_form textarea[required=true]").each(function(){
        $(this).css('border-color',''); 
        if(!$.trim($(this).val())){ //if this field is empty 
            $(this).css('border-color','red'); //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','red'); //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(), 
            'country_code'  : $('input[name=phone1]').val(), 
            'phone_number'  : $('input[name=phone2]').val(), 
            'sendto'       : $('select[name=sendto]').val(),
            'subject'       : $('select[name=subject]').val(), 
            'msg'           : $('textarea[name=message]').val()
        };

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

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

然后你的PHP将是

<?php
if($_POST)
{
$to_email = filter_var($_POST["sendto"], FILTER_SANITIZE_EMAIL); 

//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);
$country_code   = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
$phone_number   = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT);
$subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

//additional php validation
if(strlen($user_name)<4){ // 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(!filter_var($country_code, FILTER_VALIDATE_INT)){ //check for valid numbers in country code field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in country code'));
    die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
    die($output);
}
if(strlen($subject)<3){ //check emtpy subject
    $output = json_encode(array('type'=>'error', 'text' => 'Subject is required'));
    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 : (".$country_code.") ". $phone_number ;

//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\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{
    $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
    die($output);
}
}
?>