Pass JavaScript Data to PHP

Last updated: August 27, 2026.

JavaScript and PHP exchange values through HTTP. Send JSON with fetch(), then validate it on the server.

const payload = { width: screen.width, height: screen.height };
const response = await fetch("/api/screen-size.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload)
});
if (!response.ok) throw new Error("Request failed: " + response.status);
console.log(await response.json());
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=UTF-8');
$data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
$width = filter_var($data['width'] ?? null, FILTER_VALIDATE_INT);
$height = filter_var($data['height'] ?? null, FILTER_VALIDATE_INT);
if ($width === false || $height === false || $width < 1 || $height < 1) {
    http_response_code(422);
    echo json_encode(['error' => 'Invalid dimensions']);
    exit;
}
echo json_encode(['width' => $width, 'height' => $height]);

Authenticate protected endpoints, apply CSRF defenses where needed, and never trust a value merely because JavaScript generated it.

admin

admin

Leave a Reply

Your email address will not be published.