How to get JSON object in PHP?

I am trying to send a JSON object from an AJAX request to my server.

I do this using jQuery as follows:

$.ajax({ type: "POST", url: settings.ajax.post, dataType: 'json', data: basket.aggregate(Basket.EXPORT_JSON, qty), success: function(data, textStatus, jqXHR) { if (typeof settings.ajax.success == "function") settings.ajax.success(data, textStatus, jqXHR); }, error: function(jqXHR, text, e) { if (typeof settings.ajax.error == "function") settings.ajax.error(jqXHR, text, e); } }); 

The URL is pointed to this file on the server:

 <?php $to = "<my-email-address>"; $subject = "JSON test"; $message = "POST dump:\n\n"; foreach($_POST as $key=>$value) { $message .= $key . ":" . $value; } mail ($to, $subject, $message); exit; ?> 

But the POST var seems empty, although in Firebug I see that the correct data was sent to the server:

Firebug can see the JSON Object

After sending each request, the ajax error function is called with the undefined error (I think because there was no response from the server? Or I don’t know?)

+6
source share
1 answer

POST requires a pair of key values, but you just send a single value (JSON string) without a key. It must be an array.

Secondly, you need to decrypt JSON before you can use it in PHP as an array or object. json_decode() used for this.

+6
source

Source: https://habr.com/ru/post/920927/


All Articles