Error "SyntaxError: "[object Object]" is not valid JSON"

Error "SyntaxError: "[object Object]" is not valid JSON"

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

Stefan Bogdanescu

Founder & Senior Architect

Error "SyntaxError: "[object Object]" is not valid JSON"

You are seeing a SyntaxError in your browser console because the string your JavaScript code receives from the server does not match the structure of a JSON object. Specifically, you are encountering the literal text [object Object]. This usually indicates that the response body contains an HTML error page rather than pure JSON data, or that the response is being interpreted incorrectly due to dataType handling quirks in jQuery.

In your PHP handler (login.php), you correctly echo a valid JSON string:

$json = json_encode(array("success" => 1));
echo $json; // Outputs: {"success":1}

The logic seems sound, and the json_encode function produces standard JSON. However, the moment this output reaches your AJAX handler, something goes wrong before it gets parsed by JSON.parse.

The Silent HTTP Error

The most common cause for receiving [object Object] in a jQuery success callback is an unhandled exception on the server side that results in an HTTP error status code (like 403 Forbidden or 500 Internal Server Error).

When jQuery receives an HTTP error status, it does not automatically fail immediately if the response body contains content. Instead, your error handler might be triggered, but depending on how the headers are set, the response text can sometimes default to a generic message. More critically, if your PHP script encounters an exception before reaching the echo statement—such as inside LoginService::getUsersLogin() or during the session_start() process—the output will switch from JSON to an HTML error page generated by PHP.

HTML error pages often look like this:

<!DOCTYPE html>
<html>
<head><title>Error</title></head>
<body>
<pre>[object Object]</pre> <!-- Or similar generic text -->
</body>
</html>

If your JavaScript treats the response as text and attempts to parse it without verifying the HTTP status code, JSON.parse('[object Object]') (or whatever the HTML title is) will throw a syntax error.

Inspecting the Response Text

To debug this reliably, you should inspect the raw response before parsing it. In your current implementation:

success: (data) => {
    try {
        var jso = JSON.parse(data);
        console.log(jso);
    } catch (e) {
        console.log(e); // This prints "SyntaxError: [object Object]..."
        return false;
    }
}

The console.log inside the catch block confirms that data is not a valid JSON string. Before assuming the JSON is malformed, check the HTTP status code. You can modify your AJAX call to log both:

$.ajax({
    type: "POST",
    url: '/src/login.php',
    data: $(this).serialize(),
    // dataType: "json" is optional if you parse manually, but useful for auto-parsing
    success: (data, status, xhr) => {
        console.log('Status:', xhr.status);
        console.log('Raw Response:', xhr.responseText); 
        // Only parse if the status is 200 and content looks like JSON
        if (xhr.status === 200 && data.length > 0) {
            var jso = JSON.parse(data);
            console.log(jso);
        } else {
            console.error('Non-200 response or empty body');
        }
    },
    error: (xhr, status, error) => {
        console.error('AJAX Error:', status, error);
        console.log('Error Response:', xhr.responseText);
    }
});

PHP Header Configuration

Another potential pitfall is how PHP handles output. If init.php includes code that outputs headers or whitespace before the JSON echo, it can corrupt the response stream. Ensure your PHP file starts cleanly and sets the correct header explicitly:

<?php
// Remove any existing output buffers if necessary
ob_start(); 

include('init.php');
use Login\LoginService;

global $pdo;
session_start();

// ... your logic ...

header('Content-Type: application/json; charset=utf-8'); // Explicit header

if (!empty($username)) {
    try {
        $test = new LoginService();
        $user = $test->getUsersLogin($username);
        
        if (!empty($user) && $user[0]['login'] == $username) {
            echo json_encode(["success" => 1]);
            exit; // Stop script execution immediately after sending JSON
        } else {
            echo json_encode(["success" => 0]);
            exit;
        }
    } catch (Exception $e) {
        // Log the exception, but do not print it to stdout unless debugging
        // Echoing an Exception object directly might produce [object Object] if not handled
        http_response_code(500); 
        echo json_encode(["success" => false, "message" => "Server error"]);
        exit;
    }
} else {
    echo json_encode(["success" => 0]);
}
?>

Notice the exit statements and the explicit Content-Type header. If an exception occurs inside LoginService, ensure you catch it and encode a JSON error message instead of letting PHP's default error handler print an HTML stack trace or object representation.

Why [object Object] Appears

The string [object Object] is not valid JSON; it is the default string representation of an object when using print() or echo on an object in certain contexts, or when an HTML element's title attribute is rendered inside a <pre> block. If your server returns an HTML page where the <title> tag says "Object" or similar, and you parse that, you get this error.

By ensuring your PHP script always ends with exit after echoing JSON, and by handling exceptions within PHP to return valid JSON error objects, you prevent the browser from receiving mixed content types that break JSON.parse.

Our network