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 求有缘人帮我把笛卡尔坐标系转换为经纬度 有偿
  • ¥15 vue2中使用计算属性
  • ¥50 远程桌面打开Mastercam、没有许可证、物理机打开正常
  • ¥15 ubuntu安装gdal后java读取tif文件报错
  • ¥15 请问lammps怎么做两种金属连接的原子浓度分布图
  • ¥15 求jacquard数据集
  • ¥15 w10部分软件不能联网
  • ¥15 关于安装hbase的问题(操作系统-windows)
  • ¥15 novnc连接pve虚拟机报错安全协议不支持262
  • ¥15 设备精度0.03给多少公差能达到CPK1.33