Derp
Derp

Reputation: 929

Send and Decode Object Array via JSON

I have an array of People objects. I'm sending them to PHP but the way to get my objects back in PHP so I can manipulate them seems convoluted. Here's what I have, but it doesn't seem to return anything back to my AJAX Call. Right now I just have 1 Person Object in my array but I want to make sure everything is fine before I advance. In short, when I decode my JSON shouldn't it convert it to an Object in PHP? In the end I want an array of PHP objects that are People

Jquery

var people = new Array();
var person = new Person("Michael", "Jackson", 50);
localStorage.setItem(person.firstName + " " + person.lastName, JSON.stringify(person));

function Person(firstName, lastName, age)
{
    this.firstName=firstName;
    this.lastName=lastName;
    this.age=age;
}

function getStorage(){
    var tempPerson;
    for(var i = 0; i < localStorage.length; i++)
    {
        tempPerson = $.parseJSON(localStorage.getItem(localStorage.key(i)));
        people.push(tempPerson);
    }
}

function getPeople(){
    $.post(
        "people.php",
        {people : people},
        function(data) 
        {
            alert(data);
        }
    );
}

getStorage();
getPeople();

PHP

<?php
$personObj = Array();
$people = $_POST['people'];

for($i = 0; $i < count($people); $i++)
{
    foreach($people[$i] as $person)
    {
        $streamObj = json_decode($person);
    }
}

echo $personObj->$firstName;

Upvotes: 0

Views: 760

Answers (3)

Julian Tanjung
Julian Tanjung

Reputation: 14

Perhaps the PHP codes should be look like this:

<?php
$personObj = Array();
$people = $_POST["people"];

foreach($people as $p)
{
    $val = str_replace("\\","",$p);
    $personObj = json_decode($val);
}

echo $personObj->firstName;
?>

Upvotes: 0

John S
John S

Reputation: 21482

In addition to making the change suggested by @Even Hahn, you need to change the data you are posting as follows:

$.post(
    "people.php",
    {people : JSON.stringify(people)},
    function(data) 
    {
        alert(data);
    }
);

This way a single name/value pair is posted. The name is "people" and the value is a JSON encoded string of the array of Person objects.

Then when you call the following in the PHP code, you are decoding that JSON encoded string into an array on the PHP side.

$people = json_decode($_POST['people']);

I also see where you assign $personObj to an array, but I don't see where you put anything in the array.

Upvotes: 2

Evan Hahn
Evan Hahn

Reputation: 12722

Try moving your JSON decoding in your PHP:

$personObj = Array();
$people = json_decode($_POST['people']);

for($i = 0; $i < count($people); $i++)
{
    foreach($people[$i] as $person)
    {
        $streamObj = $person;
    }
}

echo $personObj->$firstName;

This is because $_POST['people'] is a JSON string which needs to be decoded.

Upvotes: 1

Related Questions