2

Possible Duplicate:
how to put javascript variable in php echo

I have a problem with PHP. I want to use a PHP variable in JavaScript. However, it does not work! $doccontent is displayed just once! Here is Test.php (the page parameter is given, e.g. Test.html):

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <?php
        $page = $_GET["page"];
        $doc = new DOMDocument();
        $doc->loadHTMLFile($page);
        $doc->formatOutput = true;
        $contentnode = $doc->getElementById('content');
        $doccontent = new DOMDocument();
        $doccontent->appendChild($doccontent->importNode($contentnode, true));
        $doccontent = $doccontent->saveHTML();
        ?>
    </head>
    <body>
        <?php
            echo $doccontent;
        ?>
        <script type="text/javascript">
            document.write("<?php echo $doccontent;?>");
        </script>
    </body>
</html>

and here is Test.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Hey</title>
        <link rel="stylesheet" type="text/css" href="Edit.css">
    </head>
    <body>
        <button id="admin"><a href="Edit.php?page=Edit.html">Edit</a></button>
        <h1>Automatica</h1>
        <div id="content">
            <h2>Header 1.1</h2>
            <p>Test</p>
            <h3>Header 1.1.1</h3>
            <p>Test</p>
            <h3>Header 1.1.2</h3>
            <p>Test</p>
            <p>Test</p>
            <h4>Header 2.0.0.1</h4>
            <p>Test</p>
        </div>
    </body>
</html>
Community
  • 1
  • 1
Agantacroxi
  • 81
  • 1
  • 10

1 Answers1

5

$doccontent almost certainly contains both " characters and new lines, either of which will break a JS string literal delimited by " characters.

The PHP json_encode function will, given a string as input, output a JS string literal. You could use that instead of echoing the raw data. (Remember not to add extra " characters around the generated string literal).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335