To send a POST request from JavaScript to a PHP backend using jQuery AJAX, call $.ajax({ url, method: "POST", data, dataType: "json" }) (or $.post(url, data, callback, "json")) with a plain object or serialized form payload. On the PHP side, read standard POST fields from $_POST (or decode raw JSON bodies from file_get_contents("php://input") if sending JSON.stringify()), and return a JSON response with Content-Type: application/json.
1. Sending Form / Object Data with $.ajax() ($_POST in PHP)
Pass a plain object as data to $.ajax() with method: "POST" and dataType: "json" so jQuery sends form-encoded parameters that PHP reads directly from $_POST and parses the JSON response automatically:
// Send a POST request with form/object fields to a PHP endpoint via jQuery AJAX
function postToPhpForm(endpointUrl, payload = {}) {
if (typeof window.jQuery !== "function" || typeof endpointUrl !== "string" || endpointUrl.trim() === "") {
return Promise.reject(new Error("jQuery and a valid PHP endpoint URL are required."));
}
const safePayload =
payload && typeof payload === "object" && !Array.isArray(payload)
? { ...payload }
: {};
return new Promise((resolve, reject) => {
window.jQuery.ajax({
url: endpointUrl,
method: "POST",
data: safePayload,
dataType: "json",
success: (responseData) => resolve(responseData),
error: (jqXHR, textStatus, errorThrown) => {
reject(new Error(`POST failed (${textStatus}): ${errorThrown || jqXHR.status}`));
}
});
});
}
// Example usage:
// postToPhpForm("/api/save-profile.php", { name: "Ali", role: "editor" })
// .then((res) => console.log("PHP response:", res))
// .catch((err) => console.error(err));
- Reads via
$_POSTin PHP: Standard jQuery objectdatamaps directly to$_POST["name"]and$_POST["role"]in PHP. - Typed JSON response: Setting
dataType: "json"parses valid JSON responses into JavaScript objects and triggerserrorif the server returns malformed JSON or HTTP errors.
2. Sending a JSON Payload (php://input in PHP)
When your PHP script expects a raw JSON request body instead of form-encoded key-value pairs, serialize with JSON.stringify(), set contentType: "application/json; charset=UTF-8", and read file_get_contents("php://input") with json_decode(..., true) in PHP:
// Send a JSON-encoded POST body to a PHP endpoint expecting php://input
function postJsonToPhp(endpointUrl, dataObj = {}) {
if (typeof window.jQuery !== "function" || typeof endpointUrl !== "string" || endpointUrl.trim() === "") {
return Promise.reject(new Error("jQuery and a valid PHP endpoint URL are required."));
}
const jsonBody = JSON.stringify(dataObj && typeof dataObj === "object" ? dataObj : {});
return new Promise((resolve, reject) => {
window.jQuery.ajax({
url: endpointUrl,
method: "POST",
data: jsonBody,
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: (res) => resolve(res),
error: (jqXHR, textStatus, errorThrown) => {
reject(new Error(`JSON POST failed (${textStatus}): ${errorThrown || jqXHR.status}`));
}
});
});
}
// Example usage:
// postJsonToPhp("/api/items.php", { items: ["a", "b"], active: true });
- Preserves nested structures: Arrays and nested objects stay intact when serialized as JSON rather than flattened by form serialization.
- PHP counterpart: In PHP, decode via
$input = json_decode(file_get_contents("php://input"), true) ?? [];.
3. Common Traps to Avoid
Connecting jQuery AJAX POST calls to PHP backends frequently runs into a few pitfalls:
- Expecting
JSON.stringify()data inside PHP’s$_POST: PHP only populates$_POSTforapplication/x-www-form-urlencodedormultipart/form-data—JSON bodies must be read fromphp://input. - Leaking PHP warnings/notices into a JSON response: Any stray PHP warning or accidental whitespace before
orecho json_encode(...)breaksdataType: "json"parsing on the client. - Skipping CSRF tokens and input validation on the PHP side: Always validate/sanitize incoming fields in PHP and verify CSRF tokens on state-changing
POSTrequests.
TL;DR: Use $.ajax({ url, method: "POST", data, dataType: "json" }) for standard $_POST form/object payloads, or send JSON.stringify(data) with contentType: "application/json; charset=UTF-8" when PHP reads file_get_contents("php://input").
