简体   繁体   中英

PHP is not able to read data sent in jQuery.ajax POST

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!

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}),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM