Sending Javascript Object to PHP via Ajax

Sending Javascript Object to PHP via Ajax

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

Stefan Bogdanescu

Founder & Senior Architect

Sending Javascript Object to PHP via Ajax

The code snippet you provided attempts to send data using a GET request, which is fundamentally incompatible with your goal of transmitting an array of IDs from JavaScript to PHP. In HTTP protocol design, GET requests are intended for retrieving resources and appending query parameters to the URL. Passing large arrays or objects via GET exposes that data in the browser's history, limits it by URL length constraints (typically around 2KB), and leaks sensitive information if not handled with extreme caution.

To send a Javascript object containing user-selected IDs, you must switch to the POST method and encode the data as JSON or form-encoded values. This shift changes how the request is constructed in both client-side JavaScript and server-side PHP.

The Client-Side Request

Your current function initializes an XMLHttpRequest object correctly but fails on two fronts: it uses GET instead of POST, and it sends no data payload at all. To transmit a Javascript array, you need to serialize that array into a string format—JSON is the industry standard for this—and attach it to the request body.

Here is how you modify the createAmenities function. First, assume you have your array of IDs stored in a variable called selectedIds. You must convert this array into a JSON string using JSON.stringify().

function createAmenities() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // Modern browsers
        xmlhttp = new XMLHttpRequest();
    } else {
        // Legacy IE support
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('message').innerHTML = xmlhttp.responseText;
        }
    };

    // Define the endpoint
    var url = "create_amenities.php";

    // Open a POST connection
    xmlhttp.open("POST", url, true);

    // Set the Content-Type header to application/json
    xmlhttp.setRequestHeader("Content-type", "application/json");

    // Serialize the array to JSON and send it
    var selectedIds = [1, 2, 5]; // Example data
    xmlhttp.send(JSON.stringify(selectedIds));
}

The critical addition here is xmlhttp.setRequestHeader("Content-type", "application/json"). This header informs the server that the body of the request contains raw JSON text, not form data. Without this header, PHP might attempt to parse the input as a standard form submission, resulting in empty variables or errors depending on how your server is configured.

The Server-Side Reception

On the create_amenities.php side, you cannot simply access the array like a traditional form variable (e.g., $_POST['ids']). When JSON data is sent via POST, it arrives as a single string in the raw request body. To extract your array, you must decode that string using json_decode().

<?php
// create_amenities.php

// Capture the raw input from the POST body
$jsonInput = file_get_contents('php://input');

// Convert the JSON string into a PHP variable (usually an array)
$data = json_decode($jsonInput, true);

// Check if decoding was successful to avoid errors on malformed data
if ($data !== null && is_array($data)) {
    $selectedIds = $data; // Now you can use $selectedIds normally
    
    // Example: Process the IDs
    foreach ($selectedIds as $id) {
        // Logic to handle the ID goes here
    }
    
    echo json_encode(["status" => "success", "message" => "Amenities created"]);
} else {
    echo json_encode(["status" => "error", "message" => "Invalid JSON data received"]);
}
?>

Using true as the second argument in json_decode() is essential. It forces PHP to return associative arrays and objects rather than stdClass objects, making your code more readable and easier to manipulate immediately after decoding.

Why Not Query Strings?

You might consider appending the array directly to the URL like create_amenities.php?id=1&id=2. While technically possible for small datasets, this approach scales poorly. A URL containing repeated parameters can quickly hit browser limits on string length and becomes difficult to read or debug. Furthermore, many web servers strip query parameters from headers if they exceed a certain size, potentially causing silent failures.

JSON remains the superior choice because it separates data transmission from URL manipulation, allows for nested structures if your requirements grow, and handles large payloads efficiently within the request body.

Modern Alternatives

While the XMLHttpRequest object works, modern front-end development often utilizes the Fetch API or libraries like Axios. These tools handle headers and JSON serialization automatically, reducing boilerplate code. However, the underlying principle remains identical: use POST, set the content type to application/json, and decode the payload on the server.

For developers using the Laravel framework specifically, handling incoming JSON payloads is streamlined through the application's request lifecycle, but the fundamental mechanics of sending a JSON object via Ajax remain consistent across all PHP environments. If you are building a larger application, consider checking resources like https://laravelcompany.com for best practices on securing your API endpoints and validating incoming JSON data structures.

Our network