du4629
2014-04-09 12:34
浏览 39
已采纳

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

I have a form that I'm using to pass some data to my AJAX action function using the standard WP Ajax techniques in my plugin:

A basic form:

<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>

In my plugin's main php file:

//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();
}

And the jQuery to perform the AJAX:

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
    });
});

This all works fine and the Ajax callaback works by outputting the response from do_ajax_signup() into the #signup_form_response div. The trouble is that the from data doesn't seem to be passed to do_ajax_signup(). The response contains only:

Your email is Array ( [action] => do_ajax_signup ) Array ( )

Why does the $_POST variable not contain my serialized form data?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douying2243 2014-04-09 12:37
    已采纳

    You are missing signup_email name attribute to <input> element.

    <input type="email" ... name="signup_email">
                            ^^^^^^^^^^^^^^^^^^^^^
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题