Bug of the day: JavaScript

on

Today’s bug comes to us courtesy of the JavaScript parser. I wrote a report for work a while back that churned out a report and used jQuery to insert a summary at the top. Like this:

print report title
(save a space for the summary)
print the report
insert a summary into the space above.

I used PHP to generate the html for the summary, and a little jQuery to put it in the space I’d left behind. At some point, it was changed to add some additional information (the 2 lines after ‘This is my summary area’) like so:


// Done in PHP
$html = 'This is my summary area';
$html .= 'The average is
'.round($someNumber, 1).'{html line break}';
$html .= 'That is all.'
echo '
{script tag}
var summary = "'.$html.'";
// put the summary html into the report summary area
$("#reportSummary").html(summary);
{end script tag}

Which made the summary stop showing up where it was supposed to. The javascript parser decided that the carriage return (hitting enter, making the hidden character n) between the word “is” and the rounding of the number meant that it should stop right there, leaving me with an unterminated string.

Apparently, what is happening is that sometimes the JavaScript parser finds n and inserts a semicolon (;) in its place.  Sometimes, that breaks your code 🙁

Changing it to this (notice that there is not a carriage return in the $html string anymore) fixed the bug! Woo!

// Done in PHP
$html = 'This is my summary area';
$html .= 'The average is ';
$html .= round($someNumber, 1).'{html line break}';
$html .= 'That is all.'
echo '
{script tag}
var summary = "'.$html.'";
// put the summary html into the report summary area
$("#reportSummary").html(summary);
{end script tag}

Leave a Reply

Your email address will not be published. Required fields are marked *