Ajax没有返回成功导致Wordpress

时间:2014-10-09 08:34:42

标签: javascript php jquery ajax wordpress

我正在尝试从数据库更新时获取返回值。我使用AJAX通过一个Wordpress插件将数据发送到functions.php中的一个函数。夹。我试图提醒成功和失败功能,它总是调用失败功能。我怎么知道AJAX响应是否成功,以便在成功时我可以做一些额外的代码。

SCRIPT

     function removeUser( department , user ){
            var value = { user_id: user , dep_name: department.id };
            $('#'+department.id+ user +"_div").hide();
            $.ajax({
                type: "POST",
                data: value
            });
        }

的functions.php

function removeUser(){
    if(isset($_POST['user_id'])){
        //echo $_POST['user_id'];
        //echo $_POST['dep_name'];

        $user_meta = get_user_meta($_POST['user_id'], 'wpwf_quotation_position');
        $user_department = json_decode ($user_meta[0]);
        //print_r ($user_department);
        //echo (json_encode($user_department));

        foreach ($user_department as $key => $value){

            if ($value == strtolower($_POST['dep_name'])){

                //print_r ($user_department);
                unset($user_department[$key]);
                $user_department = array_values($user_department);
                //print_r ($user_department);
                //echo (json_encode($user_department));
                //print_r (json_encode($user_department));
                update_user_meta( $_POST['user_id'], 'wpwf_quotation_position', json_encode($user_department));
                break;
            }
            //echo $key." : ". $value ." - " . strtolower($_POST['dep_name'])."<br>";
        }
        //echo 'ssss';
        wp_send_json($_POST);
    }

 }
 add_action('init', 'removeUser');

上面的代码运行良好,但我实际想要做的是如下,但不调用成功函数。我在这里错过了什么或做错了什么?

    function removeUser( department , user ){
            var value = { user_id: user , dep_name: department.id };

            $.ajax({
                type: "POST",
                data: value,
                success:function() {
                    $('#'+department.id+ user +"_div").hide();
                }
            });
        }

1 个答案:

答案 0 :(得分:0)

您应该使用浏览器控制台来调试此类事情。目前我说你得到'未定义不是函数'错误意味着它不能识别$,而是使用safemode jQuery(jQuery.ajax)。

你也错过了你的ajax调用中的url和动作。

function removeUser( department , user ){
        var value = { action: 'removeUser'/*assuming this is your ajax action */, user_id: user , dep_name: department.id };

        jQuery.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: value,
            success:function(output) {
                console.log(output); // have a look at the console to find your values prob something like output.user_id
                jQuery('#'+department.id+ user +"_div").hide();
            }
        });
    }

此外,我无法看到你已经将PHP函数挂钩到wp_ajax。我假设你已经这样做了?