<– Back to all “Work Diary” entries
Working on a page that fetches a list of PDF documents via an AJAX call after the document is ready. Pretty vanilla stuff – it’s a
- jQuery AJAX call that hits an endpoint and
- Displays some returned HTML (the backend builds the HTML – don’t ask because no one still here knows why…)
Anyway, ran into an issue – the frontend code was calling jQuery.parseJSON(data)
on the response (data
), but the parse attempt was failing with an error stating that there were invalid characters in the JSON.
Turns out we had recently added a MonoLogger
PHP class to the backend that basically outputs PHP errors to the JS console. It was appending some PHP errors to the JSON response, hence the parse errors.
The fix was simple – just add header('Content-type: application/json')
to the code (previously, it was just defaulting to a text content-type) and the MonoLogger
is smart enough not to append any errors to JSON responses. Done and done.
Back on the page in question, the AJAX response no longer had the PHP errors appended…but there was still a JSON parsing error in the same jQuery.parseJSON(data)
call. The same error as before: invalid characters in the JSON. 😲
Now, the solution to this dilemma is probably obvious to you as a reader, but I didn’t connect the dots. Instead, I hit up a coworker and we spent about 50 minutes dissecting the JSON response and trying to figure out why jQuery kept complaining about it.
Then it hit us – before, the response was coming back with a content-type of text (via a PHP echo
), so the jQuery.parseJSON
call was necessary to convert the text response to JSON. However, now that we had explicitly set the server’s response header’s content-type
to JSON, we were receiving a valid JSON object from the server. So, the failure was due to trying to parse a JSON object into a JSON object. 🔥
Key Takeaway
Sometimes the fix is as bad as the problem, possibly worse since you don’t naturally suspect that your fix is the culprit of your (often not-obviously new) problems.