I am calling a php file, into my HTML document using AJAX, and it is working too. The problem is that, there are few script tags in that PHP files, which works just fine if the PHP files is viewed individually. But when I call it using AJAX, those scripts are not functioning.
I am attaching my PHP code, and the screenshots below.
trial.php
<script> document.getElementById("response1").onload = function() { document.body.style.backgroundColor = "#ffa31a"; } </script> <h1 class="restitle"> Responses</h1> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "portfolio"; $conn = mysqli_connect( $servername, $username, $password, $dbname ); if ( !$conn ) { die( "Connection failed: " . mysqli_connect_error() ); } $sql = "SELECT NAME, EMAIL, MESSAGE, TIME FROM Feedback ORDER BY TIME"; $result=$conn->query( $sql ); if ( $result == TRUE ) { $i=0; ?> <script> var n = 1; </script> <?php while ($row = $result -> fetch_row()) { $i = $i+1; echo "<div class='response' id='response$i'><h1 class='responsetitle' id='responsetitle$i'><i class='fa fa-user' aria-hidden='true'></i> " . $row[0]. " <span class='responseemail' id='responseemail$i'> (". $row[1] .")</h1><hr class='responseline'><p class='responsetxt' id='responsetxt$i'>"" . $row[2] . ""</p><br /><div class='responsetimecontain'><span class='responsetime'>- " . $row[3] . "</span></div></div>"; echo "<div id='valuepipe$i' style='display:none;'>" . $i . "</div>"; ?> <script> var i = document.getElementById("valuepipe" + n).textContent; if (i % 2 == 0) { document.getElementById("response" + n).style.backgroundColor = "#ffa31a"; document.getElementById("responseemail" + n).style.color = "#f2f2f2"; document.getElementById("responseemail" + n).style.opacity = "0.6"; document.getElementById("responsetitle" + n).childNodes[0].style.color = "#f2f2f2"; document.getElementById("responsetxt" + n).style.color = "#f2f2f2"; } n++; </script> <?php } $result -> free_result(); } else { echo "Error: " . $sql . "<br>" . $conn->error; } mysqli_close( $conn ); ?>
When this file is viewed individually:
But when I call it using AJAX:
<script> var xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("main2").innerHTML = this.responseText; } xhttp.open("GET", "trial.php"); xhttp.send(); </script>
I get the following view :
Somehow all the script tags are being ignored or something. Need a solution. Any help would be appreciated.
Note: The other styles are implemented in my CSS file, so they are visible. Only the Scripts are not working
Advertisement
Answer
From the MDN reference
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
You’ll need to separate the scripts from the HTML content and either include them as part of the code that loads the content, or place them in their own script file that is loaded separately.