Hooking up a PHP function to an AJAX request: What

2019-09-09 21:54发布

The callback message is 0 and I can't figure out why.

I am trying to follow this tutorial as closely as possible, but I'm obviously missing something.

In Network on Google Chrome, each time I click the button that triggers the form to submit, I see that admin-ajax.php is being invoked and the status is 200.

What am I doing wrong?

<form method="POST" action="member-update" enctype="multipart/form-data">
    <!-- ... bunch of inputs and stuff in here -->
</form>
error_reporting(-1);
ini_set('display_errors', 'On');
$tm = new TeamManager();
add_action('wp_ajax_member-update', 'member_update');
function member_update() {
    echo json_encode("TEST ... ");
}
jQuery('.member-update-button').click(function () {
    var parentForm = jQuery(this).closest('form');
    var postData = parentForm.serializeArray();
    jQuery.ajax({
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: {
            action: 'member_update',
            postData: postData
        },
        type: "POST",
        dataType: 'json',
        success: function (retmsg) {
            alert(retmsg); // test for now
        },
        error: function () {
            alert("error"); // test for now
        }
    });
});

1条回答
不美不萌又怎样
2楼-- · 2019-09-09 22:27

Your action hook has the wrong name wp_ajax_member-update and your action is called member_update

So, your PHP code should look like this:

add_action('wp_ajax_member_update', 'member_update');
function member_update() {
    echo json_encode(array('status' => 'ok'));
    die();
}

An Ajax callback always needs to end with a die() statement in WordPress.

查看更多
登录 后发表回答