1

我有一个wordpress网站。我已经制作了一个联系表格,它是由 AJAX 发布的。这是代码:

<script type="text/javascript"> 
jQuery(document).ready(function(){
    $("#error_box").hide();
    $('#contact_form').submit(function(e){

        // prevent the form from submitting normally
        e.preventDefault();
        var na=$("#1").val();
        var email2=$("#2").val();
        var subject2 = $("#3").val();
        var message2 = $("#4").val();
   var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;   

        alert(mydata);
            $("#contact_form").css({"opacity":"0.1"});  

        $.ajax ({
            type: 'POST',
            url: $(this).attr.action,  // Relative paths work fine
            data: mydata,
            success: function(){
            $("#contact_form").css({"opacity":"1"});    
            $('#error_box').fadeIn('fast').css({"height": "auto"});
            }
        });

    });
});
    </script>

提交表单时,我希望错误框(#error_box)根据提交的数据显示一条消息,例如如果其中一个字段为空则应该显示错误,或者如果处理成功则显示成功消息并且表格已邮寄。有什么办法可以做到这一点吗?

[更新]

这是我的contact-form.php 文件(操作)

<?php   if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
    {

    if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
        echo 'EMPTY ERROR';

    } 
    else
    {
    $name = $_POST['pn2'];
    $email = $_POST['email'];
    $subj = $_POST['subject'];
    $msg = $_POST['msg'];
    $to = "ankushverma61@gmail.com";
    $mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
    echo "success";
    mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");

}
}
 ?>
4

3 回答 3

1

使用 Ajax 调用 联系表单提交表单

<form action="#" id="contactForm" method="post">  
 <input class="require" type="text" placeholder="First Name" name="firstName">    
<span class="fieldError"></span>  
<input class="require" type="text" placeholder="Last Name" name="lastName">  
<span class="fieldError"></span>   
.   
.  
.  
<input type="submit" value="Submit">  
</form>

使用 ajax 调用进行客户端验证

jQuery('#contactForm').submit(ajaxSubmit);  
function ajaxSubmit(){  
var newContactForm = jQuery(this).serialize();  
var flag = 0;  
    jQuery('.require', '#contactForm').each(function(){  
        var inputVal = jQuery(this).val();  
if(jQuery.trim(inputVal) === ""){  
            flag = 1;  
            jQuery(this).next().html("Can't be blank");  
            jQuery(this).next().show();  
        }  
        else{  
            jQuery(this).next().hide();  
        }  
    });  
    if(flag){  
        return false;  
    }  
    jQuery.ajax({  
        type:"POST",  
        url: "/wp-admin/admin-ajax.php?action=contactForm",  
        data: newContactForm,  
        success:function(data){  
            jQuery(':input','#contactForm')  
                .not(':button, :submit, :reset, :hidden')  
                .val('')  
                .removeAttr('checked')  
                .removeAttr('selected');  
            jQuery("#feedback").html(data);  
            jQuery("#feedback").fadeOut(10000);  
        },  
        error: function(errorThrown){  
            alert(errorThrown);  
        }  
    });  
    return false;  
}

在db中存储表单数据并发送邮件
在functions.php中添加以下代码

wp_enqueue_script('jquery');  
add_action('wp_ajax_addContactForm', 'addContactForm');  
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');  
function addContactForm(){  
    global $wpdb;  
    $first_name = $_POST['firstName']; $last_name = $_POST['lastName'];  
    $email = $_POST['email'];  
    .  
    .  
    .  
    if($wpdb->insert('table_name',array(  
        'first_name' => $first_name,  
        'last_name' => $last_name,  
        'email' => $email,  
        .  
        .  
        .  
    ))===FALSE){  
        echo "Error";  
    }  
    else {  
        $headers = 'From: xyz <xyz@xyz.com>';  
        $subject = "Thank you";  
        $body = "<p>Thank you</p><p>.........</p>";  
        wp_mail( $email, $subject, $body, $headers);  
        echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";  
    }  
    exit;  
}  
于 2013-08-31T05:16:04.163 回答
0

你应该使用:

      $.ajax ({
            type: 'POST',
            url: $(this).attr.action, 
            data: mydata,
            success: function(response) {  // here you receive response from you serverside 
               $("#contact_form").css({"opacity":"1"});    
               $('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
            }
        });

您的服务器操作url: $(this).attr.action,应返回插入的消息#error_box

于 2013-06-28T14:48:37.420 回答
-1

首先创建这样的表格

<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
  <fieldset>
    <label><i class="fa fa-file-text-o"></i> Register Form</label>
    <input type="text" name="firstname" placeholder="Username" id="firstname">
    <p id="firstname-error" style="display:none">Firstname Must be Enter</p>
    <input type="email" name="email" placeholder="Email address" id="email">
    <p id="email-error" style="display:none">Email Must Be Enter</p>
    <input type="submit" class="button" id="test" value="Register">
  </fieldset>
</form>

然后绑定点击并发送ajax调用

<script type="text/javascript">

 jQuery('#test').on('click', function(e) {
    e.preventDefault();
    var firstname = jQuery('#firstname').val();
    var email = jQuery('#email').val();
    if (firstname == "") {
        jQuery('#firstname-error').show();
        return false;
    } else {
        jQuery('#firstname-error').hide();
    }
    if (email == "") {
        jQuery('#email-error').show();
        return false;
    } else {
        jQuery('#email-error').hide();
    }
    jQuery.ajax({
        type: "POST",
        dataType: 'json',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: {
        action: "test", // redirect function in function.php
        firstname: firstname,
        email: email
        },
        success: function(results) {
        //console.log(results);
        if (results == "1") {
            jQuery('.register-message').text("Email already exist");
        } else {
            jQuery('.register-message').text("Register successfu");
        }

        },
        error: function(results) {}
    });
    });
 </script>

function.php添加以下代码以在表中插入数据

 <?php
     // 

     add_action('wp_ajax_test', 'test', 0);
     add_action('wp_ajax_nopriv_test', 'test');
     function test()
     {
         $firstname = stripcslashes($_POST['firstname']);
         $email = stripcslashes($_POST['email']);

         global $wpdb;
         $q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
         $res = $wpdb->get_results($q);
         if (count($res) > 0) {
             echo "1";
         } else {
             $user_data = array(
                 'firstname' => $firstname,
                 'email' => $email
             );
             $tablename = $wpdb->prefix . 'test';
             $user_id = $wpdb->insert($tablename, $user_data);
             echo "0";
         }
         die;
     }
于 2019-08-25T16:50:28.290 回答