Uncaught SyntaxError: Unexpected token '<', "
when using JSON parse on the response from AJAX request
The error Uncaught SyntaxError: Unexpected token '<', "<br />... is not valid JSON is a classic symptom of a fundamental mismatch between what your frontend JavaScript expects and what your backend is actually sending. You are attempting to parse HTML as JSON. In this specific scenario, the browser receives an HTML document instead of a JSON object because the PHP script outputs raw HTML rows directly into the response stream.
When you run JSON.parse(response) in your success callback, JavaScript expects a string that starts with { or [. Instead, it encounters the first character of your PHP output. If your PHP logic includes any echo statements outside of a strict JSON block, or if an error occurs before data generation, the response often defaults to an HTML error page (like a 404 or 500 page) or simply echoes HTML fragments like <tr> and <td>. The stack trace provided points to jquery-3.6.0.min.js, confirming this is a jQuery .ajax() call where the default expectation is JSON, but the server delivered something else.
The root cause in your PHP file is how the data is being echoed. Look closely at the loop:
while ($row = mysqli_fetch_assoc($result)) {
$date = $row['date'];
$sales = $row['total_sales'];
echo "<tr>
<td>$date</td>
<td>$sales</td>
</tr>";
}
This code outputs raw HTML table rows directly to the output buffer. When this string is sent back to the AJAX request, jQuery treats it as a response body. Since the content type header likely defaults to text/html or isn't explicitly set to application/json, and the payload itself is not JSON-encoded, your JavaScript fails immediately upon trying to parse it.
To fix this, you must ensure the PHP script outputs a valid JSON structure, even if it's an empty array. You need to wrap your data in a JSON object and use json_encode() before echoing. Additionally, you should explicitly set the content type header. Here is the corrected approach:
<?php
include "db_conn.php";
$fromDate = $_POST['fromdate'];
$toDate = $_POST['todate'];
// Validate connection and inputs
if (!$conn) {
echo json_encode(['error' => 'Connection failed']);
exit;
}
// Prepare the SQL query
$sql = "SELECT date, SUM(sales) as total_sales
FROM sales
WHERE date BETWEEN '$fromDate' AND '$toDate'
GROUP BY date ORDER BY date ASC";
$result = mysqli_query($conn, $sql);
// Initialize an array to hold the results
$salesData = [];
while ($row = mysqli_fetch_assoc($result)) {
$salesData[] = [
'date' => $row['date'],
'total_sales' => $row['total_sales']
];
}
// Close connection
mysqli_close($conn);
// Set header to inform the client this is JSON
header('Content-Type: application/json');
// Output valid JSON
echo json_encode($salesData);
?>
On the JavaScript side, you don't necessarily need to change much if the PHP logic is fixed, but it's good practice to handle errors gracefully. You might want to check if response exists before parsing or catch potential parsing errors:
$.ajax({
type: "POST",
url: "functions/search-sales_function.php",
data: { fromDate: fromDate, toDate: toDate },
success: function (response) {
// Ensure response is a valid JSON string before parsing
if (!response) return;
try {
var salesData = JSON.parse(response);
$('#sales-table tbody').empty(); // Clear existing data
for (var i = 0; i < salesData.length; i++) {
var date = salesData[i]['date'];
var sales = salesData[i]['total_sales'];
$('#sales-table tbody').append(`
<tr>
<td>${date}</td>
<td>${sales}</td>
</tr>`
);
}
} catch (e) {
console.error("Failed to parse JSON response:", e);
}
},
error: function (xhr, status, error) {
console.error("AJAX Error:", error);
}
});
There are some security considerations here as well. The current PHP code is vulnerable to SQL injection because it directly interpolates user input ($fromDate and $toDate) into the query string. While fixing the JSON issue resolves your immediate error, you should use prepared statements with bound parameters in a production environment to prevent malicious users from manipulating the database.
If you are transitioning away from raw PHP or want better type safety and routing, frameworks like Laravel handle these HTTP responses and JSON encoding automatically. For instance, returning a collection from a controller method in Laravel will automatically serialize it to JSON with the correct headers. If your project grows, exploring a framework might be a valid long-term strategy for managing API endpoints more robustly.
Finally, ensure that no other code runs after echo json_encode(). Any stray whitespace or additional HTML generated by subsequent logic (like closing database connections or including files that echo output) will corrupt the JSON stream and trigger this exact error again. Keep the output buffer clean until the very last line of your script.