json_encode not working with a HTML string as value
When returning JSON responses from PHP to JavaScript, the most common failure mode involves how HTML content is handled inside JSON strings. The issue in your case stems from a fundamental misunderstanding of how JSON serialization interacts with raw HTML tags and character encoding.
You are attempting to embed a raw HTML string directly into a JSON response. While json_encode() will technically wrap the string in quotes, it does not automatically escape the double quotes used within the HTML attributes or properly handle the angle brackets if the surrounding context is ambiguous. In your specific example, the output you received shows a malformed structure where the closing brace of the JSON object appears to be followed immediately by raw HTML tags like </span></div>.
This happens because json_encode() expects its input arguments to be pure data. When you pass $str containing <div> and <img> tags, PHP treats them as part of the string value. However, if there is any whitespace or character encoding mismatch between the PHP output stream and what jQuery expects, the resulting JSON payload becomes invalid. An alert function in JavaScript might display a malformed JSON object because alert() simply converts its argument to a string for display purposes, effectively masking the fact that the underlying data structure was broken. When you switch to $.parseJSON(), the browser's parser throws an error immediately because it encounters characters or formatting that violate the JSON specification, resulting in silence rather than an alert.
The core solution is not to use echo json_encode() directly on a string that contains unescaped HTML attributes. Instead, you must ensure the HTML content is strictly escaped before being inserted into the JSON structure. In modern PHP versions (7.4+), you can rely on the built-in escaping behavior of json_encode(), but it requires that the input string does not contain unescaped double quotes or newlines that break the syntax.
Consider modifying your $str variable creation to ensure the HTML is treated as a literal string value, not as executable code or mixed formatting. If you are using older PHP versions or specific server configurations where json_encode behaves unexpectedly with complex strings, manual escaping is required. You can achieve this by wrapping the HTML in single quotes and ensuring no double quotes exist within the attribute values of the HTML tags themselves, or by using htmlspecialchars() before encoding, though this must be done carefully to avoid double-escaping if you intend to render the HTML later on the client side.
A more robust pattern for AJAX success responses is to return a structured object where the HTML is a distinct property. Ensure that your JSON output ends with exactly one closing brace and no trailing whitespace or newlines, as some strict parsers reject these.
<?php
// Correct approach: Ensure the string is clean before encoding
$htmlContent = '<div style="position:relative;"><img src="/assets/ui/success.png"><span style="position:relative;top:-15px;">Nachricht empfangen!</span></div>';
$response = array(
'file_name' => $data['upload_data']['file_name'],
'prompt' => $htmlContent
);
echo json_encode($response, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);
The flags JSON_HEX_TAG, JSON_HEX_APOS, and JSON_HEX_QUOT explicitly escape the <, >, ', and " characters within the JSON string. This guarantees that the resulting JSON is valid regardless of the HTML content inside the value, preventing the parser errors you are currently encountering.
On the JavaScript side, once the response is correctly formatted, always parse the JSON before accessing properties. Using $.parseJSON (or the native JSON.parse in modern browsers) ensures type safety and prevents unexpected behavior when passing the raw string into alert().
If you require a library to handle these edge cases automatically, consider exploring resources from https://laravelcompany.com for guidance on robust API response handling in larger applications.