2

I am very puzzled.

I passed an key value pair object from jquery to php. and alert it back out again successfully but if I go to the php page. it says the data is null or undefined index.

below is my jquery

$('#test').click(function(){
   var obj= {
                'key': 'value',
            };
$.ajax({
                url: "../folder/file.php",
                type: "POST", 
                data: {
                    'obj' : obj
                },
                dataType: "JSON",
                success:function(data){
                    alert(data);
                }

            });
}); 

below is my php

$data = $_POST['obj']; // this is line 1
echo json_encode($data); // this is line 2

With the above code, when I click test button, I will get alert value. but if I go to the php page after I clikced the test button. the page says Notice: Undefined index: obj on line 1, and null on line 2.

Why?

I am getting alerted the value I put in. So it must mean the data went through and back. but the php page says it is null.

codenoob
  • 539
  • 1
  • 9
  • 26

2 Answers2

2

$_POST['myobj']; is an array, not a json string.

While it is a JS object when you use it as the value of data in your ajax method, it is translated into post data unless you explicitly set contentType. By default the content type is application/x-www-form-urlencoded; charset=UTF-8

Because you are using the default content type:

$_POST['myobj']['key1'] should be the value of key1 for example.

Use var_dump on the object to see it better, and understand the structure of it.

i.e.

var_dump($_POST['myobj']);
skrilled
  • 5,350
  • 2
  • 26
  • 48
  • hmm var_dump($_POST['myobj']) says null. and $_POST['myobj']['key1'] both didnt work. if I change echo json_encode($data); to just echo. I was alerted object Object. I think it has something to do with this – codenoob Aug 24 '16 at 23:35
  • Try just `var_dump($_POST)` now. There is literally no logical reason why `$data = $_POST['myobj']; echo json_encode($data);` would work like you suggested but replacing that code with what I put above would not. – skrilled Aug 24 '16 at 23:39
  • Unless you're saying that jQuery is returning the alert with `null` in it, which makes sense, since you explicitly set `dataType` to `json`. If that's what you're saying, then remove the dataType from json so that you can see the data being dumped. – skrilled Aug 24 '16 at 23:40
  • if I dont echo json_encode. I either get no alert or an object Object alert. var_dump($_POST) gets array(0) { }. – codenoob Aug 24 '16 at 23:41
0

I think when you post JSON objects to PHP you can read them via php://input. php://input contains the raw POST data and therefore is a string that need to be JSON encoded:

// Read all
$json = file_get_contents('php://input');
// String -> array (note that removing `true` will make it object)
$obj = json_decode($json, true);
// Print it
var_dump($obj);

Small demo (test.php)

<?php
var_dump($_POST);

// Read all
$json = file_get_contents('php://input');
// String -> array (note that removing `true` will make it object)
$obj = json_decode($json, true);
// Print it
var_dump($obj);
?>

Output using curl to call it:

$ curl -X POST -d '{"test": "value"}' localhost/test.php
array(0) {
}
array(1) {
  ["test"]=>
  string(5) "value"
}

Finally, if you want to be able to pass JSON data and URL parameters at the same time, use the following:

function buildRequest(){

    // Get Data
    $json = file_get_contents('php://input');

    // Form the request from the imput
    if ($json!=""){
        $_REQUEST = array_merge_recursive($_REQUEST,json_decode($json, true));
    }
}

buildRequest();
var_dump($_REQUEST);

Calling the above with both URL and data parameters results in:

curl -X POST -d '{"test": "value"}' localhost/test.php?param=value2
array(2) {
  ["param"]=>
  string(6) "value2"
  ["test"]=>
  string(5) "value"
}

Let me know if the above works for you.

urban
  • 5,392
  • 3
  • 19
  • 45