Question

JavaScript code:

var data = {"hiSO": "my very complex - nested objects/arrays - data object"};

var j = jQuery.noConflict();
j.ajax({
  type: "POST",
  url: "postTestingResult.php",
  contentType: "application/json; charset=utf-8",
  data: {"data": JSON.stringify(data)},
  dataType: "json",
  success: ajaxSuccess,
  error: ajaxError
});

PHP Code:

header('Content-Type: application/json');

if(!empty($_POST['data'])) {
    $data = json_decode($_POST['data']);

    //do things with data

    echo json_encode(array("success" => "thanks for the info!"));
} else {
    echo json_encode(array("error" => "'data' is not set or is NULL"));
}

No matter how I structure the data, $_POST['data'] always seems to be empty (specifically, Undefined). If you want a full copy of the data object I am using, check out this JSFiddle. Appreciate the help, thank you!

Was it helpful?

Solution

You've told the server you're sending JSON (via contentType: "application/json; charset=utf-8"), but you're not sending JSON, you're sending URI-encoded data. This is because you've given jQuery an object for the data option (an object with one property, whose value is a JSON string).

Your PHP code expects URI-encoded data, so to fix it just remove the contentType option so jQuery uses its default.

If you really want to send JSON instead (which would require changing your PHP), change

data: {"data": JSON.stringify(data)},

to

data: JSON.stringify(data),

or

data: JSON.stringify({data: data}),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top