Unexpected end of JSON input from an ajax call

Unexpected end of JSON input from an ajax call

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

Stefan Bogdanescu

Founder & Senior Architect

Unexpected end of JSON input from an ajax call

The SyntaxError: Unexpected end of JSON input exception is one of the most persistent and misleading errors in front-end development. It appears frequently when handling Ajax responses, often causing frustration because the error message suggests a broken payload on the receiving end, while the actual culprit usually lies in how the server constructs that payload or how the client interprets it.

In the scenario you described, the application shifts from standard form submission to an asynchronous request. The core issue stems from a mismatch between the data being sent by the client and the way the server expects to receive it. Specifically, your jQuery configuration sends data as a JSON string, while your PHP script attempts to read the input as a named array element.

When you set contentType: false, processData: false, and pass JSON.stringify(postDeleteID) in the data field, you are bypassing jQuery's default behavior of automatically serializing objects or arrays into a query string or form data format. Instead, you are sending a raw JSON string (e.g., "42"). However, because contentType is explicitly set to false, the browser might not send the correct Content-Type: application/json header, or more critically in this specific legacy setup, jQuery might still attempt to parse the response based on its internal defaults if the dataType logic gets confused.

The primary failure point is in your PHP code:

if(!empty($_POST)){
    $deletePostID = $_POST['deletePostID'];
    // ...
}

This line attempts to access $_POST['deletePostID']. The $_POST superglobal only populates when the request contains form fields with a name attribute (typically application/x-www-form-urlencoded or multipart/form-data). When you send raw JSON without the correct headers or wrapping, PHP often ignores the body for POST requests or populates $_GET depending on specific server configurations, or simply returns an empty array if the content type isn't recognized as form data.

If $_POST is empty, the script skips the logic block entirely and hits the end of the file without echoing anything. Since you have a header('Content-Type: application/json') inside the conditional block, but no echo statement outside of it, the response becomes an empty string (""). When jQuery receives this empty string but expects JSON (due to dataType: 'json'), it attempts to parse an empty buffer and throws the "Unexpected end of JSON input" error immediately.

To resolve this, you must align the data transmission method on both ends. The most robust approach for simple value transmission is to stick to standard form data rather than raw JSON strings unless using frameworks like Laravel that handle JSON routing natively.

First, modify your jQuery call to use standard form data:

$(document).ready(function(){
    $(".post__delete").on("click", function(e){
        var postDeleteID = $('.deleteID').val();

        $.ajax({
            url: "ajax/deletePost.php", 
            type: "POST",             
            data: { deletePostID: postDeleteID }, // Remove JSON.stringify and set processData to true (default)
            dataType: 'json',
            contentType: false, // Usually not needed if using standard data object
            cache: false,
            processData: true,  // Allow jQuery to serialize the data object
            success: function(data) {
                console.log("Deleted:", data);
            },
            error: function (request, status, error) {
                console.error("Error:", request.responseText);
            }
        });

        e.preventDefault();
    });
});

Second, simplify the PHP handler to rely on $_POST directly without the conditional check that leads to silent failures:

<?php
include_once("../classes/Post.class.php");
session_start();
$post = new Post();

// Ensure we only process if data exists
if (!empty($_POST['deletePostID'])) {
    $deletePostID = $_POST['deletePostID'];

    // Perform the deletion logic here
    // Assuming deletePost returns a boolean or status code
    if ($post->deletePost($deletePostID)) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['status' => 'success']);
    } else {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['status' => 'failed']);
    }
} else {
    // Handle missing data explicitly to prevent empty responses
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(400);
    echo json_encode(['error' => 'Missing deletePostID']);
}
?>

If you are building a larger application where JSON payloads are the norm, consider migrating this logic to a Laravel project. Laravel's routing and request handling abstract away many of these header and serialization pitfalls. You would define a route like POST /api/posts/{id} which automatically binds the ID from the URL and handles JSON parsing in the controller, ensuring that request('deletePostID') or $request->input('id') works reliably regardless of how the front-end sends the data. This approach eliminates the ambiguity of $_POST vs JSON string handling entirely.

The key takeaway is to ensure that every path your PHP script can take results in a valid JSON response, including error conditions and edge cases where input is missing.

Our network