0

Why can't AJAX load another HTML page with JavaScript? It loads HTML,CSS,PHP etc... but not JavaScript. Is AJAX supposed to work like that? If so how can I load another HTML page that contains JS with AJAX?

A simple example what I mean

a.php

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "b.php", true);
  xhttp.send();
}
</script>

</body>
</html>

b.php

<!DOCTYPE html>
<html>
<body>
<h1>b</h1>
<script>
document.write("Hello World!");
</script>

</body>
</html>

Screenshot of response:
AJAX response screen shot

Al.G.
  • 4,327
  • 6
  • 31
  • 56
  • Possible duplicate of [Can scripts be inserted with innerHTML?](https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml) – yuriy636 Aug 31 '17 at 20:05

1 Answers1

0

Because the javascript code you'll get via ajax is a simple string and not executed. You have to eval() the code in the script tag like:

Example:

<script id="helloworld">
document.write("Hello World!");
</script>

JS:

var jsCode = document.getElementById('helloworld').textContent;
eval(jsCode);

Edit by request:

if (this.readyState == 4 && this.status == 200) {
    var demoElement = document.getElementById("demo");
    demoElement.innerHTML = this.responseText;
    var scriptTags = demoElement.getElementsByTagName('script');

    for(i = 0; i < scriptTags.length; i++) {
        eval(scriptTag[i].textContent);
    }
}
Tyr
  • 2,810
  • 1
  • 12
  • 21
  • Well how would it look in my two example do I put both your code sections in a.php or b.php? –  Aug 31 '17 at 20:32
  • So how can I integrate your example into my example? –  Aug 31 '17 at 21:15