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 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了