1

Following dropdown:

<select id='dropdown' name='dropdown' onchange='showChart(this.value)'>
<option value="1">Foo</value>
<option value="2">Bar</value>
</select>

Calls this javascript function onchange:

<script type="text/javascript">
        function showChart(str1) {
            if (str1 == "") {
                document.getElementById("chartContainer").innerHTML = "";
                return;
            }
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("chartContainer").innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.open("GET", "../ajaxpage/chart.php?charttype=" + str1);
            xmlhttp.send();
        }
    </script>

chart.php?charttype looks like this:

<?php
$charttype = $_GET['charttype'];

if ($charttype == "1") {
    echo "<p>test1</p>";
    echo "<script type='text/javascript'>
        alert('test1');
    </script>";
} else {
    echo "<p>test2</p>";
    echo "<script type='text/javascript'>
        $(document).ready(function() {
          alert('test2');
        });
    </script>";
}

?>

Everything seems to work. The test1 and test2 in paragraph tags are rendered correctly in the graphContainer div onchange of the dropdown. However, the javascript is not executing. How come generated javascript does not execute, and how do I fix this?

Thanks.

EDIT

Here is the extremely foul (but working) workaround:

<img src="../images/loaded.gif" alt="" 
     onload="Code To Execute Here;this.parentNode.removeChild(this);" />
Matthias
  • 12,704
  • 13
  • 35
  • 56
  • Nope, firebug doesn't seem to give me any errors. The script is also correctly rendered into the HTML when I check the source. – Matthias Apr 08 '12 at 12:50
  • Does `http://....../ajaxpage/chart.php?charttype=1` actually return valid data? – mplungjan Apr 08 '12 at 12:51
  • Yup, I can do an echo of the $charttype on the page with PHP and that gives me the correctly passed value. – Matthias Apr 08 '12 at 12:53
  • possible duplicate of [Can scripts be inserted with innerHTML?](http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml) – epascarello Apr 08 '12 at 12:55
  • I would avoid at-all-costs having one programming language write another language, or mixes languages together in the same spot. It might seem fine today... but you're going to come back to this one day, or maybe your friend, and it's going to feel like a claw hammer right to the teeth when you need to fix it. – Incognito Apr 08 '12 at 13:01

1 Answers1

4

JavaScript is not evaluated with innerHTML.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 1
    Yep, and this is one of the reasons that you shouldn't use `innerHTML` to "load" pages. – Jeffrey Sweeney Apr 08 '12 at 12:54
  • Any workarounds to make it work? I'm not that very familiar with html/js, let alone ajax. – Matthias Apr 08 '12 at 12:54
  • @Matthias Perhaps you could use an `iframe`. If the file you're loading is just a script, you could try dumping the content into a script tag and then `appending` it to the document (although there are security risks to doing this). – Jeffrey Sweeney Apr 08 '12 at 12:58
  • Unfortunately, it's not just a script. Depending on the value of the dropdown, I have to generate a graph (with Highcharts) so I have to combine PHP and Javascript in order to generate the correct graph depending on data from a database. Just simplified things a bit to ask my question. – Matthias Apr 08 '12 at 13:01
  • @Matthias `iframes` are probably the most ideal solution then. They can cause headaches if used incorrectly or unnecessarily, but if the only alternative is loading an external page with `innerHTML` or `document.write` (and they are in this case), you'll probably have more luck with an `iframe` looking at the newly generated page. – Jeffrey Sweeney Apr 08 '12 at 13:13
  • Workarounds: http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml – Janus Troelsen Apr 08 '12 at 13:14
  • JanusTroelsen: eval() doesn't work. Tried that already... JeffreySweeney: How would I do that then? Can't really find examples that would apply in this particular situation. – Matthias Apr 08 '12 at 13:17
  • `document.getElementById("iframe").setAttribute("src", "newPageAddress.php")` – Jeffrey Sweeney Apr 08 '12 at 13:24
  • 1
    USE A LIBRARY! JQuery, MooTools, Etc all do this for you! – epascarello Apr 08 '12 at 13:33
  • @epascarello libraries do the exact same thing that the OP is trying to do. Well... pick your poison. – Jeffrey Sweeney Apr 08 '12 at 13:36
  • The eval() solution involves evaluating the code inside the script tags, not the entire html chuck! Read through the duplicated topic I posted. – epascarello Apr 08 '12 at 13:42
  • Alright. Accepted for answer because (some) of the comments pointed me in the right direction. – Matthias Apr 08 '12 at 14:19