I have an extremely simple JSON object that looks like the following:
var data =
{
"id" : 1
}
I then decode this in PHP:
$decoded_data = json_decode(stripslashes($_POST['data'])); //this works
$id = intval($decoded_data->id); //in my debugger this is equal to 1 as expected
I then pro开发者_StackOverflow社区ceed to pass the $id variable into a function that queries the database and returns a set of 'Sub Activities'
$sub_activities = alp_get_all_sub_activities($id); //this function works as expected and returns the correct result set
Now that I have the Sub Activities for the designated $id, I attempt to access them using a loop:
foreach ($sub_activities as $activity) {
echo __("<td><a id='" . $activity->id . "' href='' title='Activity'><div style=' border: 3px solid purple; width: 200px; height: 200px; overflow: scroll;'>" . $activity->name . "<br />" . $activity->id . "<br />" . $activity->description) . "</div></a></td>";
}
My problem is: echo displays nothing when $id is set to intval($decoded_data->id), but when I hardcode $id = 1 then everything works as expected and shows in my browser. I'm not quite sure how to approach this problem, because my debugger is telling me that when I set $id = intval($decoded_data->id); that $id is equal to 1. I can do arithmetic with this number and it seems like it behaves as any integer would, but for some reason echo and print() will not display anything.
If anyone has any insight I'd really appreciate your input.
try accessing the value like this:
$id = $decoded_data->{'id'};
$id = (int)$decoded_data->{'id'};
$id = intval($decoded_data->{'id'});
$id = (int)$decoded_data->id;
Instead of this:
$id = intval($decoded_data->id);
Thinking about this a little more is JSON treating the integer as a boolean? Could you try
var data =
{
"id" : "1"
}
This turned out to be a problem with ajax in Wordpress with Buddypress installed. Buddypress was sending the request elsewhere for its own purposes. I just created my own javascript namespace object and rerouted the data. Here are tutorials that helped me figure this out:
http://codex.wordpress.org/AJAX_in_Plugins
http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
JSON now works perfectly. Thanks for the help!
精彩评论