Posting Array to PHP using ajax

Posting Array to PHP using ajax

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

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Key in AJAX POST Data

When debugging an AJAX request where $_POST appears empty despite the JavaScript side confirming a populated array, the culprit is rarely the JSON stringification itself. It is almost always a mismatch between how you are sending the data and how your server expects to receive it. In the specific scenario described, the developer constructs a single stringified JSON array—something like ["routeID:testRoute", "custID:testCustID"]—and then wraps that entire blob inside a named key called data.

The resulting payload looks like this:

{
  "data": "[\"routeID:testRoute\", \"custID:testCustID\"]"
}

This is the critical failure point. On the server side, when PHP receives an AJAX POST request where the data is wrapped in a single key (like data), $_POST becomes an associative array containing one entry: ['data' => 'the_json_string']. It does not automatically parse that string into individual form fields. When the PHP script attempts to access $routeID = $_POST['routeID'], it looks for a top-level key named routeID. Since the key is actually nested inside data, and because the value of data is still a raw string rather than an object, the specific keys like routeID do not exist at the root level. Consequently, PHP treats these undefined indices as empty strings, resulting in blank values being inserted into the MySQL database.

To fix this without relying on complex parsing logic in your controller, you must align the payload structure with how standard form submissions work. The most straightforward approach is to send a flat object where each key matches exactly what $_POST expects. Instead of creating an array of strings and stringifying that entire list, construct a single associative array (or object) where the keys are your database columns.

In JavaScript, you can achieve this by passing the values directly into the data property:

$.ajax({
    type: "POST",
    url: "AddtoDatabase.php",
    data: {
        routeID: routeID,
        custID: custID,
        stopnumber: stopnumber,
        customer: customer,
        latitude: lat,
        longitude: lng,
        timestamp: timeStamp
    },
    cache: false,
    success: function(response) {
        alert("OK");
    }
});

By doing this, the browser sends a standard form-encoded payload. When PHP receives this, $_POST['routeID'] will immediately contain "testRoute". This eliminates the need for manual string parsing or JSON decoding on the server side, reducing overhead and potential security risks associated with injection attacks if the input isn't sanitized correctly before use.

If you must send a JSON payload (for instance, if you are using application/json as the content type), you should ensure that the data property itself is an object, not an array of strings. You would stringify an object like { routeID: "testRoute", custID: "testCustID" }. Your PHP script can then use json_decode(file_get_contents('php://input'), true) to extract the variables, provided the content type header is set correctly. However, for traditional form submissions via AJAX, sticking to the flat associative array pattern remains the industry standard because it maps 1:1 with $_POST.

One common pitfall in this scenario involves mixed data types. If your JavaScript sends numbers (like lat = 10) and strings (like routeID), ensure consistency. Sending a number in JSON keeps it numeric, whereas form encoding often converts everything to strings anyway. While PHP handles both flexibly, explicit typing in the database schema should guide how you construct the payload. Always validate that the keys in your JavaScript object match the column names in your SQL INSERT statement exactly, including case sensitivity if your operating system or web server configuration enforces it.

Finally, consider the security implications of concatenating user input directly into SQL queries. The provided code snippet uses string interpolation:

$sql = "INSERT INTO Locations ... VALUES ('$routeID', '$custID'...)";
mysqli_query($mysqli, $sql);

This is highly vulnerable to SQL injection if any of the POST variables contain a single quote or other special characters. Regardless of whether you fix the AJAX payload structure, you must replace this concatenation with parameterized queries using mysqli_real_escape_string (deprecated in newer contexts) or, preferably, prepared statements. Prepared statements handle escaping automatically, ensuring that data integrity is maintained and the database remains secure against malicious payloads.

Our network