How to solve SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in ajax and php

How to solve SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in ajax and php

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

Stefan Bogdanescu

Founder & Senior Architect

Solving the SyntaxError: JSON.parse Issue in AJAX and PHP

When working with asynchronous requests, a SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data error is one of the most immediate red flags. It tells you exactly what is happening: the JavaScript engine received a string that does not begin with { or [, which are the required starting characters for valid JSON objects and arrays.

In your specific scenario, the error originates in the success callback of your jQuery AJAX call. You are attempting to execute var x = JSON.parse(data);. This line assumes that the string returned by emp.php is a pure JSON object. However, looking at the console output you provided, the response begins with an HTML table structure generated by PHP's error reporting mechanism, specifically an Xdebug notice about an undefined index.

The browser receives a payload that looks like this:

<br /><font size='1'><table class='xdebug-error xe-notice'...>...</table></font>
{"employee":"FMCSC00015","ename":"Tom", ...}

Because the string starts with <br /> instead of {, JSON.parse() fails immediately. This is a classic case where PHP's error reporting settings are interfering with the JSON response stream.

The Root Cause: PHP Error Reporting

The core issue lies in how your PHP script handles errors. You have code that attempts to access $jsn['EMPID'] without verifying if the key exists first. If the Oracle package PKG_PAYROLL.get_emp_by_id returns null or if the data retrieval logic fails silently, $jsn might not be populated as expected, or the index check fails. Consequently, PHP triggers a "Notice" that you logged in your sample response.

By default, PHP will echo these notices directly to the standard output (STDOUT). When this output is sent over HTTP, it becomes part of the body returned to the client. Since jQuery's dataType: 'html' setting tells it to treat the response as raw text, it includes the error log at the top. Even if you had set dataType: 'json', the first characters would still be invalid HTML tags, causing a parse failure before any deserialization occurred.

To resolve this, you must suppress PHP notices and warnings when generating JSON responses. You can do this by modifying the logic in emp.php to check for the existence of keys before accessing them:

$jsn = $jsonarray['employee'] ?? null;

if (!$jsn) {
    echo json_encode(['error' => 'Employee data not found']);
    exit;
}

$array = array(
    'employee'   => $jsn['EMPID'],
    'ename'      => $jsn['ENAME'],
    'designation'=> $jsn['DESIGNATION'], 
    'department' => $jsn['DEPARTMENT'],
    'secdivision'=> $jsn['SECDIVISION']
);

echo json_encode($array);

Additionally, ensure that PHP error reporting does not output to the screen during production. You can temporarily set ini_set('display_errors', 0); in your environment or use a logging mechanism like Monolog if you are building a larger application.

Handling the Response in JavaScript

While fixing the backend is critical, robust frontend code should also handle unexpected responses gracefully. In your AJAX configuration, you are using dataType: 'html'. This forces jQuery to treat the response as an opaque string. If you switch this to dataType: 'json', jQuery will automatically attempt to parse the response. However, because the response contains leading HTML tags, the automatic parser will still fail unless the source is clean.

If you cannot guarantee that the PHP output is always pure JSON (for instance, if you need to handle legacy error states), you should strip non-JSON content before parsing. A common utility function for this is:

function parseSafeJson(text) {
    const text = text.trim();
    // Extract the first valid JSON object or array from the string
    const start = text.indexOf('{');
    const end = text.lastIndexOf('}') + 1;
    
    if (start !== -1 && end > start) {
        return JSON.parse(text.substring(start, end));
    }
    
    throw new Error('Invalid JSON response received');
}

This approach is defensive programming. It acknowledges that the backend might occasionally send an error log but ensures that valid JSON embedded within it is still extracted and usable.

Best Practices for AJAX Integration

When integrating PHP with AJAX, always ensure that your echo statements are the very last thing executed in the script. Any output buffering from previous include, require, or error logs will corrupt the JSON structure. Furthermore, avoid mixing HTML formatting tags like <br /> or <table> with JSON data unless you are explicitly building a JSON-encoded HTML string for templating engines like Mustache or Twig, which is not the case here.

If you are using Laravel, the framework provides robust helpers to handle this separation of concerns. You can use response()->json() instead of echo json_encode() to ensure proper headers and error handling. For example:

return response()->json($array);

This ensures that even if an exception is thrown, Laravel will catch it and return a standardized JSON error response rather than mixing HTML with your data stream.

Finally, always validate the structure of your Oracle package output before encoding it. If oci_execute fails or returns null, handle that state explicitly to prevent undefined index notices from leaking into the API response.

Our network