繁体   English   中英

使用Ajax的wordpress update_user_meta onclick

[英]Wordpress update_user_meta onclick with Ajax

我正在尝试通过Wordpress中的Ajax调用update_user_meta。 我不断获得“成功!” 控制台日志,但不返回任何数据,并且用户meta字段未更新。

在按钮上单击general.js:

var newViewPreference = jQuery(this).attr('id');
jQuery.ajax({
    url: '/wp-admin/admin-ajax.php',
        data: {
            'action':'update_view_pref',
            'viewPref' : newViewPreference
        },
        success:function(data) {
            console.log(data);
            console.log("success!");
        },
        error: function(errorThrown){
            console.log(errorThrown);
            console.log("fail");
        }
});

的functions.php

add_action( 'wp_ajax_update_view_pref', 'update_view_pref');
function update_view_pref() {
    if(empty($_POST) || !isset($_POST)) {
        ajaxStatus('error', 'Nothing to update.');
    } else {
        try {
            $user = wp_get_current_user();
            $viewPref = $_POST['viewPref'];
            if ($viewPref == 'toggle-grid') {
                update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'grid' );
            } elseif ($viewPref == 'toggle-list') {
                update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'list' );
            }
            die();
        } catch (Exception $e){
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }
}

有人能指出我要去哪里了吗? 谢谢。

将$ _POST更改为$ _REQUEST是可行的。

谁能解释为什么$ _POST无效但$ _REQUEST无效吗?

我是通过单击按钮(不是表单)将数据提交给ajax请求的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM