0

My HTML Page load via an onclick-event external HTML Code with JS code inside in a div-box. The JS code is not executed.

simplifyed Example:
index.php

// Full HTML document with the XMLHttpRequest() to extern.php

extern.php

<?php
header("Content-type: text/html; charset=utf-8");

$concat = '<div>many HTML content generated with PHP.</div>';
$concat .= '<script>';
$concat .= 'console.log("TEST");'; // In original the script modified the HTML above.
$concat .= '</script>';

echo $concat;
?>

The external content with script are loaded in the div-box, no problem.
Problem: The console.log("TEST") dont work.

Please only solutions with pure Javascript. Please no JQuery or similar.

Edit: No other questions have a solution for Ajax, but only for innerHTML.
Solution:

  • In the external content write a <script> tag with inside your Javascript code that will be executed.
  • In the XMLHttpRequest (Ajax) passed the external content to a function().
  • In the function():
    • insert the external content in the HTML document via innerHTML.
    • get the innerHTML from the <script> tag in the external content.
    • execute the <script>-innerHTML with a eval().

Tip: Use only a function() in the external content <script> tag. This function() will be triggerd by loading the external content via Ajax. Save this function() in the HTML document or in a separate *.js file and embedded it in the HTML document.

Working:

  • a custom_function() with javascript (for manipulating the external content) is saved in a customscript.js.
  • the customscript.js is embedded in the HTML document.
  • when the XMLHttpRequest() is called
    • the external content is requested.
    • the external content is passed to a insert_function() with innerHTML.
    • the insert_function():
      • insert the external content via innerHTML in the HTML document.
      • example:
        • var ajaxcontent = document.getElementbyId("extern-content");
        • ajaxcontent.innerHTML = external_content;
      • get the innerHTML from the external content <script> tag and execute it.
      • example:
        • eval(ajaxcontent.getElementsByTagName("script")[0].innerHTML);

EDIT: Duplicate??? (fail)
The linked Question is: "Can scripts be inserted with innerHTML?". My question will NOT insert! It should be grabbed the script-content and eval it.

Malama
  • 145
  • 1
  • 8

0 Answers0