Send JSON data from Javascript to PHP?

Send JSON data from Javascript to PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Sending JSON from JavaScript to PHP: The Complete Workflow

Sending structured data from a browser to a server is a fundamental operation in modern web development. When you need to transmit complex objects—like user forms, filter parameters, or API payloads—the standard approach is to serialize them into JSON and send them as raw request bodies. PHP handles this natively without requiring external libraries, provided you configure the HTTP headers correctly.

The core mechanism relies on the fetch API (or jQuery/axios) sending a payload with the header Content-Type: application/json. If you omit this header or set it incorrectly, PHP's superglobals like $_GET or $_POST will not contain the data in the expected format. Instead, you must access the raw request body using php://input.

Here is the practical implementation using vanilla JavaScript and PHP.

The JavaScript Side

In your frontend code, you construct a JSON object and pass it to the fetch function as the second argument. This ensures the payload remains stringified during transmission.

const data = {
    username: "dev_user",
    role: "admin",
    preferences: {
        theme: "dark",
        notifications: true
    }
};

fetch('/api/receive', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) 
});

The JSON.stringify() function is critical here. While some libraries auto-serialize objects, the native fetch API expects a string in the request body. Without this step, you risk sending an object literal that the server cannot parse.

The PHP Side

On the backend, the most common mistake is attempting to access the data via $_POST. If the header Content-Type: application/json is present but the code looks for $_POST['username'], the variable will be empty or undefined because the stream was not read into the superglobal.

To handle JSON requests correctly, you must use file_get_contents('php://input'). This reads the raw input stream directly from the request body. Once retrieved, you parse the string into a native PHP array using json_decode().

<?php
// Read raw input from the request body
$input = file_get_contents('php://input');

if ($input !== '') {
    $data = json_decode($input, true); // Decode to associative array
    
    if (json_last_error() === JSON_ERROR_NONE) {
        // Access data safely
        $username = $data['username'] ?? '';
        $role = $data['role'] ?? null;
        
        echo "Received username: " . htmlspecialchars($username);
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON payload']);
    }
}
?>

Handling Cookies and Sessions

A frequent architectural concern when moving to this pattern is session management. Traditional form submissions often rely on PHP sessions tied to cookies sent via $_POST or standard HTML forms. However, raw JSON requests usually lack a session cookie in the body; they are transmitted in the Cookie header by the browser automatically.

If you need to maintain user state, ensure your PHP application is configured to read the session.cookie_name. In Laravel, for example, this is handled automatically within the kernel's request lifecycle. In vanilla PHP, you must explicitly call session_start() before accessing any superglobals, even if the data comes from JSON.

<?php
session_start(); // Must be called early in the script
// Now $_SESSION['user_id'] is accessible
?>

Framework Considerations

If you are building a larger application, raw PHP might feel verbose or brittle for handling API contracts. Frameworks like Laravel abstract away much of this boilerplate. They automatically map incoming JSON to properties on request models using attributes like $request->json()->user(). This reduces the risk of type mismatches and simplifies validation logic.

For teams looking to streamline these interactions, resources like https://laravelcompany.com offer insights into modern PHP frameworks that handle JSON serialization and deserialization out of the box.

Conclusion

The transition from form-based submissions to JSON payloads is seamless in PHP, provided you respect the HTTP protocol boundaries. By reading php://input and decoding the string, you retain full control over your data structure while adhering to modern API standards.

Our network