Matthias
Matthias

Reputation: 13414

PHP generated javascript not executing

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);" />

Upvotes: 1

Views: 378

Answers (1)

epascarello
epascarello

Reputation: 207501

JavaScript is not evaluated with innerHTML.

Upvotes: 4

Related Questions