The Hidden Trap in jQuery AJAX POST Requests
A common stumbling block for developers migrating from older PHP versions or mixing frameworks involves handling JSON payloads sent via AJAX. You might be sending a perfectly formed JSON string using JSON.stringify and expecting it to arrive intact in your server-side handler, only to find that $_POST appears empty. If you are inspecting the network tab in your browser and seeing the payload correctly formatted, yet your PHP script echoes "Noooooooob" because isset($_POST['categories']) returns false, the issue is almost certainly a configuration mismatch rather than a bug in jQuery or PHP itself.
The root cause lies in how different HTTP clients and servers interpret the request body based on the Content-Type header. When you use jQuery's .ajax() method with an object like {'categories': tmp}, jQuery automatically sets the Content-Type header to application/x-www-form-urlencoded. This is a legacy behavior designed for traditional form submissions, not modern JSON APIs.
Consequently, when your PHP script receives this request, it does not see raw JSON. Instead, it sees an encoded string where the key-value pairs are separated by ampersands (&) and equal signs (=), typically looking like categories=%5B%22id%3A21.... The standard PHP superglobal $_POST is specifically designed to parse this format using application/x-www-form-urlencoded or multipart/form-data. Because your JSON string contains characters that get encoded (like brackets and quotes), the raw data never lands in $_POST['categories'].
To fix this, you must explicitly tell both the client and server that you are sending JSON. On the client side, you need to set the contentType option within your jQuery AJAX call to 'application/json'. This instructs jQuery to send the raw JSON string without URL encoding it. More importantly, you must configure the PHP script to read the raw input stream instead of relying on the automatic parsing of $_POST.
Here is how you should adjust your JavaScript:
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
contentType: 'application/json', // Explicitly set content type
data: JSON.stringify({'categories': tmp}), // Ensure data is a string
success: function(msg) {
alert(msg);
}
});
Note that data should remain a string when contentType is application/json. If you pass an object directly, jQuery might try to encode it anyway. The cleanest approach is often passing the raw JSON string directly as the data value.
On the server side, you need to switch from $_POST to php://input. This stream provides access to the raw body of the HTTP request regardless of the Content-Type header. Since PHP automatically parses $_POST, $_GET, and $_SERVER based on specific headers, bypassing that automatic parsing requires reading the input stream manually.
Update your save_categories.php as follows:
<?php
// Read the raw input stream
$jsonString = file_get_contents('php://input');
if ($jsonString) {
// Decode the JSON into a PHP array
$decodedData = json_decode($jsonString, true);
if (json_last_error() === JSON_ERROR_NONE) {
// Access your data structure
if (isset($decodedData['categories'])) {
$categories = $decodedData['categories'];
// Process $categories here
} else {
echo "No categories found in payload.";
}
} else {
echo "Invalid JSON received: " . json_last_error_msg();
}
} else {
echo "Noooooooob";
}
?>
This approach ensures that the complex nested array structure generated by your nestable plugin is preserved exactly as sent. By using php://input, you decouple your logic from the specific Content-Type header, making your endpoint more robust against future client changes. However, it does introduce a responsibility: you must validate that the input is valid JSON before decoding it to prevent fatal errors or security issues if malicious data is injected.
If you are already using a framework like Laravel for future projects, this manual handling becomes unnecessary. In such environments, you can utilize middleware or form request classes that automatically parse JSON bodies into native PHP objects or arrays, abstracting away the php://input and Content-Type nuances entirely.