update_user_meta doesn’t work with AJAX

I try to keep user subscription in a metadata var.
The function is called by AJAX. Ahe AJAX is called but the metadata does not seem updated on frontend.

Here is the code:

jQuery

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#tags_list a').click(function(){
            myid = $(this).parent("li").attr('id');
            $.post(
                '<?php echo admin_url( 'admin-ajax.php' ) ?>', 
                {
                    'action': 'change_subscription',
                    'type': 'post_tag',
                    'term_id': myid
                }, 
                function(response){
                    $('#'+myid).toggleClass('checked');
                }
            );
            return false;
        });
    });
</script>

AJAX

add_action('wp_ajax_change_subscription', 'change_subscription');
function change_subscription() {
if (!empty($_POST['term_id']) && !empty($_POST['type'])) {
    $user = wp_get_current_user();

    update_user_meta( $user->ID, 'hannit_meta', 'My Value' );
    die();
} else
    die($st);
}

Front-end check:

<?php
            $user = wp_get_current_user()->ID;
            $tags = get_user_meta( $user->ID, 'hannit_meta', true);
            echo "<!-- u:".$user." val ".$tags."-->";
            ?>

Result: <!-- u:236 val-->

What am I missing here?

2 Answers
2

First You can get rid of nasty globals in your AJAX call. I’m not sure what the $st variable that you were output is all about so I’ve excluded, but you can include as you wish –

add_action('wp_ajax_change_subscription', 'change_subscription');
function change_subscription(){

    if(!empty($_POST['term_id']) && !empty($_POST['type'])) :

        $user_id = get_current_user_id();       
        update_user_meta( $user_id, 'hannit_meta', 'My Value' );

    endif;

    die();

}

For testing, it looks like you were querying the meta incorrectly, so pleaes try this –

$user_id = get_current_user_id();
$tags = get_user_meta( $user_id, 'hannit_meta', true);
echo "<!-- u:".$user_id." val ".$tags."-->";

Leave a Comment