Line Breaks, Carriage Returns from PHP to Javascript to HTML
My gosh, I have struggled with this conversion too many times! I shall endeavour to put an end to my troubles and anyone else’s who develops across all the layers.
The Problem: PHP is outputting the value of a textarea within javascript, which in turn is causing the javascript error “unterminated string literal…â€
The Long Answer: Line Breaks, Carriage Returns, and Newline characters have different character representations depending on which language you’re in, and more so - how the character is being displayed. It seems when you pull a newline character from a mysql db, and display it in php it is displayed in ASCII format. I, myself am not all too familiar with it, but I do know it seems to be the format that the db stores data. Check out this ascii conversion table to see what all of our html characters translate to in ascii.
The Short Answer: You need to convert your ascii line breaks (both Line Break “\n†& Carriage Return “\râ€) to javascript line breaks:
Solution:
$escaped_value = str_replace(chr(13),'n',$report[$column_name]); $escaped_value = str_replace(chr(10),'',$escaped_value);
Explanation: In the first line, we use str_replace to convert chr(13) to javascript line break “\nâ€. Then in the second line, we convert the other possible line break (or carriage return) chr(10) to nothing (so as to prevent duplicate line breaks).