dsxjot8620 2015-01-27 21:42
浏览 51
已采纳

Wordpress update_user_meta onclick with Ajax

I'm attempting to update_user_meta via Ajax call in Wordpress. I keep getting a 'success!' console log, but no data is returned and the user meta field is not being updated.

general.js on a button click:

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

Anyone able to pinpoint where I'm going wrong? Thanks.

  • 写回答

1条回答 默认 最新

  • douan4106 2015-01-28 02:20
    关注

    Changing $_POST to $_REQUEST worked.

    Can anyone explain why $_POST didn't work but $_REQUEST did?

    I was submitting the data to the ajax request via a button click (not a form).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大