I'm having an issue reading response data from a wordpress ajax function.
I created the script to pull the data and echo a json encoded response:
function upd_user_data() {
global $wpdb;
if( isset($_POST['user'] ) ) :
$userid = $_POST['user'];
$userdata = array();
$userdata['key'] = get_usermeta( $userid, 'upd_key' );
$userdata['hits'] = get_usermeta( $userid, 'upd_hit' );
$signups = get_users( 'meta_key=upd_referred_user&meta_value='.$key );
$userdata['signups'] = $signups;
$userdata['signup_count'] = count($signups);
echo json_encode($signups);
else :
echo json_encode('Error: no user set.');
endif;
die();
}
So, I make the call:
<?php function upd_get_user_data() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.upd-user').on('click', function(){
var upduser = $(this).attr('userid');
var data = {
action: 'upd_user_data',
user: upduser
};
//Test to make sure it's grabbing the user id attr
$('#test').html(upduser);
$.post(ajaxurl, data, function( data ) {
$('#upd-top-row').html( data );
});
});
});
</script>
<?php } ?>
The userid is being grabbed from the .attr() just fine as it's value posts to test. But, the response from the ajax into #upd-top-row
is only '0', which I assume means an empty result or array.
From reading up on $.post, it's able to detect the response format, so I don't need to define it. Is this true? I've alway used $.ajax, but $.post seems simpler.
Add this code below the upd_user_data()
function.
add_action("wp_ajax_upd_user_data", "upd_user_data");
add_action("wp_ajax_nopriv_upd_user_data", "upd_user_data");