Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive JSON object in PHP?

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

I'm doing this with JQuery like this:

  $.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 to be empty, even though in Firebug I can see that the correct data was sent to the server:

Firebug can see the JSON Object

After each request is sent, the ajax error function is called, with an undefined error (I guess because there was no reply from the server? Or I don't know?)

like image 545
Ozzy Avatar asked Jul 19 '12 23:07

Ozzy


1 Answers

POST needs key value pairs, but you're just sending it one value (a JSON string) without a key. It needs to be an array.

Secondly, you need to decode the JSON before you can use it in PHP as an array or object. json_decode() is used for that.

like image 81
Sarke Avatar answered Nov 05 '22 02:11

Sarke