I am having trouble accessing json values return from an ajax call.
Here is the call:
$.ajax({
type: 'POST',
data: 'user_id=' + user.user_id + '&user_login='+ user.user_login,
//dataType: 'json',
url: 'http://###/user-stats.php',
success: function(data){
alert(data);
//alert(data.games_won[0]['winner_id']);
//console.log(data);
if(data) {
$('#hand-stats-display').html(data);
//$.mobile.changePage( "#user-home", { transition: "fade"} );
}else{
$('.messages').html("No stats available at this time... Please try again later.");
//alert(data);
}
},
error: function(){
//console.log(data);
alert('Ajax Login Request â');
}
});
Here is the PHP:
$myrows['hands_won'] = $wpdb->get_results( "SELECT * FROM wp_winners WHERE user_id=" . $user_id );
if ( $myrows )
{
//echo('Rows Exist â');
//echo "List of {$meta_key1} posts, sorted by {$meta_key2}";
foreach ( $myrows as $id )
{
$creds[]=$id;
//echo('MyRows: ' . $myrows[id]);
}
}
//echo "Winner ID:" .$myrows[0]->win_id;
//echo "Winner 2 ID:" .$myrows[1]->win_id;
echo json_encode($creds);
It returns a json object like:
[{"win_id":"1","user_id":"1","game_id":"1"},{"win_id":"2","user_id":"1","game_id":"2"}]
I can not seem to access these with the javascript I am using. Any advice is appreciated.
Looks like you want to use something like
result = $.parseJSON(data)
. Then you can access the data withresult.win_id
, for example.As an aside, you should sanitize the input to that database query using
prepare
with something like:$wpdb->get_results( $wpdb->prepare( "SELECT * FROM wp_winners WHERE user_id=%d", $user_id ) );