6

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?)

9
  • 1
    What does var_dump($_POST); output? Commented Jul 19, 2012 at 23:24
  • an empty array @ShaquinTrifonoff Commented Jul 19, 2012 at 23:24
  • Have a look at this post link Commented Jul 19, 2012 at 23:31
  • 1
    You can send data using .load. I thought that if ajax isn't working, then maybe load would work ? Commented Jul 19, 2012 at 23:37
  • 1
    @Ozzy Glad you got the answer. Commented Jul 19, 2012 at 23:38

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Sure, he forgot parameters. But still, FF sent a string, can't that be accessed in PHP somehow?
@Bergi well, I don't think its worth answering that, I just changed the data param to data: {json:basket.aggregate(...)} and I got the JSON string now :)
@Bergi - for the record, as he only submitted a string, it was treated as the key of the key-value pair. He could have accessed it by examining the array array_keys($_POST), which would have contained the string (in an array with any other POST keys).
@Ozzy The error in callback is presumably because the script is not sending any headers, which are evaluated as premature exit for a valid HTTP response.
or you can simply set the header to 200 ok precisely speaking. header('HTTP/1.1 200 OK')
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.