Trouble decoding JSON string with PHP

Posted by Anthony on Stack Overflow See other posts from Stack Overflow or by Anthony
Published on 2011-11-28T09:01:49Z Indexed on 2011/11/28 9:51 UTC
Read the original article Hit count: 218

Filed under:
|
|

I'm trying to send an array of objects from JS to PHP using JSON. I have an array of players as follows:

var player;
var players = new Array();
//loop for number of players
player = new Object();
player.id = theID;
players[i] = player;

Then my AJAX call looks like this:

JSONplayers = JSON.stringify(players);
$.ajax({
type: "POST",
url: "php/ajax_send_players.php",
data: {
    "players" : JSONplayers
}

On the PHP side the decode function looks like this

$players = $_REQUEST['players'];
echo var_dump($players);
$players = json_decode($players);
echo 'players: ' .$players. '--'. $players[0] . '--'. $players[0]->id;

Debugging in chrome, the JSON players var looks like this before it is sent: JSONplayers: "[{"id":"Percipient"},{"id":"4"}]"

And when I vardump in PHP it looks OK, giving this: string(40) "[{\"id\":\"Percipient\"},{\"id\":\"4\"}]"

But I can't access the PHP array, and the echo statement about starting with players: outputs this: players: ----

Nothing across the board...maybe it has something to do with the \'s in the array, I am new to this and might be missing something very simple. Any help would be greatly appreciated.

note I've also tried json_decode($players, true) to get it as an assoc array but get similar results.

© Stack Overflow or respective owner

Related posts about php

Related posts about JavaScript