Fabian
Fabian

Reputation: 111

JS post Object via JSON

I am aware, that there are many questions regarding this topic in general... however, so far I haven't found a solution to my specific problem:

I have objects, looking something like that:

var myArray = [];
var ArrayObject = {
    power: 10,
    name: 'arrayobject'
}
myArray.push(ArrayObject);

var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);

Now I would like to post this data to php:

post("./output.php", myObject,'post');

Well, this does not work... I also tried it with

var myJSON = JSON.stringify(myObject);

and on PHP Side with

//$myObj = json_decode($_GET['myObject']);

but that does not work as well... if I remove the 'myArray' from 'myObject' that works, but having all data in one object would be very nice.

Can anyone tell me how to do that or point me in the right direction?

Thank you very much!

Upvotes: 1

Views: 51

Answers (1)

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

If you make request like this

function test(){

    var myArray = [];
    var ArrayObject = {
        power: 10,
        name: 'arrayobject'
    }
    myArray.push(ArrayObject);

    var myObject = {};
    myObject.Name = "test";
    myObject.myArray = myArray.slice(0);

    jQuery.post('output.php', {
        data: {
            myObject:myObject
        },
    }, function(data) {

        console.log(data);

    });
}

then you access the data in PHP like

$_POST['data']['myObject']

Whole $_POST will look alike

array (
    'data' => 
    array (
        'myObject' => 
        array (
            'Name' => 'test',
            'myArray' => 
            array (
                0 => 
                array (
                    'power' => '10',
                    'name' => 'arrayobject',
                ),
            ),
        ),
    ),
)

You don't need to json_decode it automatically does

Upvotes: 1

Related Questions