0

I am loading html content into a div using XMLHttpRequest() It works fine with just html, but if I add any javascript functions to the html content, I get a function undefined error when I try to use them.

When "main_table_html.php" finishes loading, the javascript function inside called "we_are_loaded()", should be executable, but it returns an error of undefined.

I inherited this code and I'm not sure what to do here:

Here is the code:

// Main Load XML Doc Function
function loadXMLDoc(url,cfunc) {         
    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=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
} // end of load xml doc


function btnClick(item) {
    loadXMLDoc(item,function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("MainContent").innerHTML=xmlhttp.responseText;
            if(item == 'main_table_html.php'){ 
                we_are_loaded();
            }
        }
    }); 
    return "complete"; 
}
wazz
  • 4,953
  • 5
  • 20
  • 34
user3101337
  • 364
  • 8
  • 24
  • I don't know at this point, but have you looked at the html result after loading it? Is the function actually on the page, in script tags? I imagine loading script that way might be a problem but see if it's actually there first. In the end, if you can take out the script from the html content and add it to the script above, you'll be done, and safer. – wazz Oct 20 '19 at 20:40
  • Hi wazz. It is loading the content in script tags, I can see it in the developer console. I am adding the js to that file because it's easier to manage. – user3101337 Oct 20 '19 at 20:43
  • Where does “we_are_loaded” come from? It is not shown in the code; this is not a minimal test/example case. – user2864740 Oct 20 '19 at 20:50
  • Generally, assigning innerHTML does NOT execute script tags for security reasons. This is not a new behavior change and there are some crafty ways that script tags and extracted and executed via “eval” or similar - this is extra library behavior and NOT part of the DOM or reasonable expectations when assigning innerHTMl in a modern browser. – user2864740 Oct 20 '19 at 20:51
  • Looks like from the information above it's because scripts can't be inserted with innerHTML. I will just load the js externally and forget about doing it through innerHTML – user3101337 Oct 20 '19 at 20:56
  • How can I mark this as answered? – user3101337 Oct 21 '19 at 01:06

0 Answers0