Retrieving serialize data in a PHP file called using AJAX

Retrieving serialize data in a PHP file called using AJAX

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

Stefan Bogdanescu

Founder & Senior Architect

Decoding Serialized Data from AJAX POST Requests

When building asynchronous applications, you often encounter the scenario where a JavaScript client sends a serialized string to a server-side script, expecting that script to reconstruct the original data structure. The core challenge lies in understanding exactly what format that string takes and how to safely reverse the process on the PHP side without losing data integrity or introducing security vulnerabilities.

Understanding the Transmission Format

In the provided scenario, the client uses jQuery's .serialize() method. This function iterates through all form controls and appends them into a URL-encoded string. Crucially, for an array of checkboxes named box[], this method generates a flat list where each selected checkbox appears as a separate key-value pair. If checkboxes with values '1' and '2' are selected, the resulting string sent to the server will look like:

box[]=1&box[]=2

Note that the name retains the brackets [], but since .serialize() does not include the name=box[] part in a way that preserves the array structure in a single variable key (unless box was the only name), the data is flattened. However, looking closely at the specific AJAX call provided:

data: "box1="+str,

The user explicitly wraps the serialized string inside a new variable named box1. This means the server receives a single parameter box1 whose value is the entire serialized string of the form. The PHP code attempts to retrieve this with $box = $_POST['box1'];, which correctly captures the raw string "box[]=1&box[]=2".

The Deserialization Process

To access individual values, you must deserialize the string back into an associative array or a multi-dimensional array that represents the form state. PHP provides unserialize() for this purpose, but you must first wrap the flat string in a way that unserialize can interpret it as an array, or use explode to parse the raw query string manually.

If you attempt to pass the raw string "box[]=1&box[]=2" directly to unserialize, it will fail because unserialize expects a serialized resource representation (like those generated by serialize()), not a URL-encoded string. You need to reconstruct the array format first.

Option 1: Manual Parsing with explode

The most robust and version-independent approach is to parse the URL-encoded string manually. Since the data is flat, you can split it by the ampersand delimiter and then extract key-value pairs.

$boxString = $_POST['box1']; // "box[]=1&box[]=2"

// Split the string into individual parameters
$params = explode('&', $boxString);

$boxes = [];

foreach ($params as $param) {
    // Handle empty strings that might occur at the end of the string
    if (empty($param)) {
        continue;
    }

    // Parse key and value. The key is "box[]" and value is "1" or "2"
    list($key, $value) = explode('=', $param, 2);

    // Remove the brackets from the key to create a consistent index
    $cleanKey = str_replace('[]', '', $key);

    // Check if the key already exists in our array
    if (isset($boxes[$cleanKey])) {
        // If it exists, append the value (handling multi-value keys)
        $boxes[$cleanKey][] = $value;
    } else {
        $boxes[$cleanKey] = $value;
    }
}

// Resulting structure: ['box' => ['1', '2']]
print_r($boxes);

This method gives you a predictable array structure where ['box' => ['1', '2']] allows you to iterate over the selected options easily.

Option 2: Using explode for direct access

If you know the keys are identical and simply need a list of values, you can simplify the logic:

$selectedValues = [];
foreach (explode('&', $_POST['box1']) as $pair) {
    if ($pair === '') continue;
    
    $parts = explode('=', $pair);
    $key = str_replace('[]', '', $parts[0]);
    $val = $parts[1];
    
    // Initialize the key if it doesn't exist
    if (!isset($selectedValues[$key])) {
        $selectedValues[$key] = [];
    }
    
    $selectedValues[$key][] = $val;
}

Security Considerations and Best Practices

A critical pitfall in this pattern is the handling of serialized data. Never rely on unserialize() with data coming from a user-controlled source unless you strictly validate the input first. While explode is generally safer because it avoids executing code contained within the string, unserialize() can execute arbitrary code if the payload contains objects.

In this specific case, since the client uses .serialize(), the data consists only of strings and simple booleans (for checkboxes). However, if your application evolves to handle text inputs or file uploads via AJAX, blindly trusting $_POST contents becomes dangerous. Always sanitize input before processing.

Additionally, consider using Laravel's request handling if you are adopting the framework. Laravel provides helper methods like request()->input('box1') which automatically decode JSON if sent as application/json. If you stick to application/x-www-form-urlencoded, the manual parsing approach remains valid but requires careful attention to encoding issues (like spaces encoded as +).

Conclusion on Implementation

To access each value, treat the incoming string as a flat list of key-value pairs rather than a ready-to-use array. By splitting the string and normalizing the keys by removing the brackets, you can reconstruct the original form state reliably. This approach avoids the complexity of serialization libraries while maintaining full control over data validation and security checks on the server side.

Our network