Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object via jQuery post to php

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.

enter image description here

Than on the php part I only do this:

 $data= $_POST['data'];
 print_r($data);

The output of print_r is:

enter image description here

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?

like image 952
Phil LA Avatar asked Dec 19 '22 13:12

Phil LA


1 Answers

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]);

example

like image 124
Ryan Avatar answered Dec 24 '22 01:12

Ryan