3

I have this jQuery $.ajax script:

var data = JSON.stringify( selected_products );

$.ajax({ type: "POST", 
    url: "addtocart.php", 
    data: data, 
    dataType: 'application/json'
}); 

And I am posting this to a really simple PHP script:

$selected_products = json_decode($_POST['data'], true);
print_r($selected_products);

This is an example of what I'm sending; this is outgoing data in Chrome DevTools:

data:[{"id":"RECOLOURBALM","option":"Black","quantity":1},{"id":"TOWELS","quantity":1}]

However this is the console readout for the response:

Array
(
)

I think the request is succeeding and data is being passed, but the responses are all empty.

What am I doing wrong?

aaron
  • 39,695
  • 6
  • 46
  • 102
Aaranihlus
  • 143
  • 2
  • 13

2 Answers2

3
$selected_products = json_decode($_POST['data'], true);
echo $selected_products[0]['id'];
echo '<br>';
echo $_POST;
echo '<br>';
var_dump($_POST);

add data to your post

You are now getting null that's because of the stringify given there. Please change the code like this.It will surely work.

var data=[{"id":"RECOLOURBALM","option":"Bordeaux","quantity":1},{"id":"TOWELS","quantity‌​":1}];
//data = JSON.stringify(data);
$.ajax({ 
    type: "POST", 
    url: "addtocart.php", 
    data: {'data':data}, 
    success:function(returndata){
        console.log(returndata);
    }
});

Remove the stringify.

Darshan
  • 345
  • 6
  • 24
1

If the Content-Type is set to application/json, you have to receive data as follows.

$data = json_decode(file_get_contents('php://input'), true);

$_POST will receive the data from request, which has Content-Type: x-www-form-urlencoded(Form Data)

Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28