0

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.

2

1 Answer 1

1

I tried to emulate some data:

var message = [
    {id: "90"},
    {"id": 123},
    {"id": 456},
    {"id": 87.5},
    {"id": 123.1}
];

I used your javascript and added a success handler to use the output of the PHP file:

JSONplayers = JSON.stringify(message);
alert(JSONplayers);
$.ajax({
    type: "POST",
    url: "ajaxTest.php",
    data: {
        "players": JSONplayers
    },
    success: function(data) {
        $('#myId').html(data);
    }
}); 

Then I tweeked your PHP a little bit:

<?php
    $players = $_REQUEST['players'];
    $json = json_decode(stripslashes($players),true);
    foreach($json as $row) {
        echo $row['id'] . '<br />';
    }
?>

This kicks out a new line for each entry and references it by its key (id).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.