PHP, JavaScript, HTML – Correct Echoing of HTML in JavaScript

htmljavascriptPHP

A colleague and I were discussing how to echo HTML inside of javascript code. Specifically, in a situation similar to this:

new Element('div', {
    html: '{long string of HTML goes here!}'
}.inject($('content'));

Short snippets seem to work well in this situation, but what if we were echoing a large set of data? The line would then become very long, and hard to debug (because who horizontally scrolls?!)

A problem also lies in the fact that besides its length, all quotes used need to be escaped, especially if the javascript code is being echo'd from the server side, in which case one of the quote marks would be "used up", per se.

One solution would be to break up the long line of HTML code:

new Element('div', {
    html:   '{long string of HTML goes here!}' +
            '{some more HTML goes here}' +
            '{and even more...}'
}.inject($('content'));

Another solution provided involved including an addslashes()'d server-side include, which involves a second file. Although I suppose it is also possible to define all of the to-be-included HTML in a php variable, and echo it when it is needed:

<?php
    $html = addslashes('{html content}');
?>

new Element('div', {
    html: '<?=$html?>'
}.inject($('content'));

Which method is best in terms of code readability, efficiency, and security?

Best Answer

The addslashes method is NOT reliable. Instead, do:

new Element('div', {
    html: <?= htmlspecialchars(json_encode($html)) ?>
}.inject($('content'));

addslashes() is a braindead deprecated method of escaping text for SQL usage. It's not intended for Javascript. That's what JSON is for. It'll convert your PHP data (simple variable, object, array, etc...) into what's guaranteed to be syntactically correct Javascript.

JSON (or javascript) embedded in HTML needs to be properly escaped for HTML. That is why it is wrapped in htmlspecialchars(). Consider that JSON will NOT encode <, >, &, and others because they are valid characters in a quoted JSON string.

However, since you're just inserting one block of html into JS, you could just have

<div id="seekrithiddenhtml" style="display: none">
<?= $html ?>
</div>

from which you can then do a simple cloning in javascript.

Related Topic