Reputation: 163
I know, there are plenty of questions out there, but none of them worked for me.
I build an array with normal javascript objects in javascript and sent it via jquery.post
to the server. However on the server, I can't access the data using php $obj->value
. I tried json_decode/encode
and so on.
This is what console.log(data)
gives me, before sending it to the server.
Than on the php part I only do this:
$data= $_POST['data'];
print_r($data);
The output of print_r is:
And thats how my Jquery post looks like:
$.post("programm_eintragen.php",{
data: data,
}).success(
function(data){
//success
}).error(
function(){
console.log("Error post ajax " );
},'json');
Could somebody tell me:
how I can access my object properties on the php site properly?
I also get tried to access non object ....
or php interprets the json object as a string an data[0]
returns me [
.
I thought, I could do it like this:
$data[0]->uebungen[0]
Am I just being silly and missing something?
Why is this whole json sending to php thing such a problem?
Upvotes: 4
Views: 10483
Reputation: 3820
This is how I do it:
JavaScript
var data_obj = {
"function": "create_customer",
};
$.post({ url: "src/index.php", dataType: "json", data: data_obj }, function (data) {
});
PHP
$json_obj = json_decode(json_encode($_POST));
$function = $json_obj->{"function"};
URL is the path relative to index.html
.
Upvotes: 0
Reputation: 14649
In JavaScript, your're not actually sending a JSON encoded string, your are just sending form data. To actually send a JSON string, you need to convert it (the object) to a string.
$.post("programm_eintragen.php",{
data: JSON.stringify(data),
});
On the receiving side (php script) you will have a JSON string. You can decode it.
$data = json_decode($_POST['data'], true);
var_dump($data[0]['uebungen'][0]);
However, these steps are not necessary. All the json_encoding can be avoided by just accessing the array directly. For this example, ignore the above javascript, and don't change anything in your code.
$data = $_POST['data'];
var_dump($data[0]['uebungen'][0]);
Upvotes: 12