WordPress Ajax动作函数不接收表单数据

时间:2014-04-09 12:34:00

标签: php jquery ajax wordpress

我有一个表单,我正在使用我的插件中的标准WP Ajax技术将一些数据传递给我的AJAX动作函数:

基本形式:

<form role="form" id="signup_widget_form" method="post" action="#">
    <input name="action" type="hidden" value="do_ajax_signup" />
    <div class="input-group">            
        <input type="email" class="form-control" id="signup_email" placeholder="Email">
        <label for="signup_email"  class="sr-only">Email</label>
        <span class="input-group-btn">
            <button type="submit" class="btn btn-default">Sign Up</button>
        </span>
    </div>    
</form>
<div class="alert" id="signup_form_response"></div>

在我的插件的主要php文件中:

//Instantiate the AJAX handler and load our jQuery
add_action( 'wp_enqueue_scripts', 'signup_enqueue_scripts' );
function signup_enqueue_scripts(){
    wp_enqueue_script( 'signup-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) );
    wp_localize_script( 'signup-ajax-handle', 'signup_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

// The AJAX add actions
add_action( 'wp_ajax_do_ajax_signup', 'do_ajax_signup' );
add_action( 'wp_ajax_nopriv_do_ajax_signup', 'do_ajax_signup' );


// This will perform the server-side AJAX stuff and return a response
function do_ajax_signup(){
   $email = $_POST['signup_email'];
   echo "Your email is " . $email; //this is passed back to the javascript function
   print_r($_POST);  print_r($_GET);
   die();
}

执行AJAX的jQuery:

jQuery(document).ready(function($){
    $('#signup_widget_form').submit(function(){

    var form = $(this),
        formData = form.serialize(),
        formMethod = form.attr('method'), 
        responseMsg = $('#signup_form_response');

        $.ajax({
            url: signup_ajax.ajaxurl,
            data: formData,
            method: formMethod,
            success: function(data) {
                responseMsg.html(data);
            }
        });
        return false; //prevent form from submitting
    });
});

这一切正常,Ajax callaback通过将do_ajax_signup()的响应输出到#signup_form_response div来工作。麻烦的是,from数据似乎没有传递给do_ajax_signup()。响应仅包含:

  

您的电子邮件是数组([action] =&gt; do_ajax_signup)数组()

为什么$_POST变量不包含我的序列化表单数据?

1 个答案:

答案 0 :(得分:2)

您缺少signup_email<input>元素的名称属性。

<input type="email" ... name="signup_email">
                        ^^^^^^^^^^^^^^^^^^^^^