I want to post Javascript Array Object via Ajax to PHP. Then at PHP end, i still want to use that object as an true Array. Below is my approach so far still not successful in terms of using the incoming object as an Array
at PHP side. I can just parse it as the string
.
Javascript:
var myObj = {
fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 },
mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 },
sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 }
}
Then, Javascript/JQuery to send via AJAX:
$.ajax({
type: "POST",
url: "ajax.php",
dataType: "JSON",
data: { "data" : JSON.stringify(myObj) }
}).success(function( response ) {
alert(response);
});
Then parse at PHP:
$data = json_decode( $_POST["data"] );
echo json_encode( $data["fred"] );
echo json_encode( $data["fred"]["apples"] );
echo json_encode( $data["fred"]->apples );
echo json_encode( $data[1] );
- Any of above
echo
returns blanks, back to the browser.
But when i:
$data = json_decode( $_POST["data"] );
$to_string = print_r( $data, true ); //<-- Used these instead
echo json_encode( $to_string ); //<-- Used these instead
.. it returns following big strings back to the browser:
stdClass Object
(
[fred] => stdClass Object
(
[apples] => 2
[oranges] => 4
[bananas] => 7
[melons] => 0
)
[mary] => stdClass Object
(
[apples] => 0
[oranges] => 10
[bananas] => 0
[melons] => 0
)
[sarah] => stdClass Object
(
[apples] => 0
[oranges] => 0
[bananas] => 0
[melons] => 5
)
)
- So seems data is there, but how can i parse this data as in the proper truely
ARRAY
manner atPHP
end, please?