0

I have a HTML that uses this function for loading another PHP with Ajax:

   function LoadContent(n,func)
{           
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState== 4 && xmlhttp.status == 200)
        {
            document.getElementById("div-content").innerHTML=xmlhttp.responseText;
        if(typeof(func)==='undefined')
                {
                // nothing
                }
            else
                {
                eval(func);
                }

        }
    }
    xmlhttp.open("GET",n,true);
    xmlhttp.send();
}

So far, all OK. The PHP to be loaded generates a HTML which contains a

<script> 
function foo() { 
alert('hello'); 
} 
</script>

And the original HTML calls the loader with javascript:LoadContent('file.php','foo()') , but foo() is not called. The eval() line says "no such function" in Chrome.

How could I manage it so, after Ajax loading, the JavaScript function which would reside in the loaded html would be executed?

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • If the HTML you posted is the *response* sent by the server, you also have to add it to the document before you do anything with it. However, I'd argue that this, loading JS from the server and passing a string of JS which should be evaluated after the the content is loaded, is a bad approach. – Felix Kling Sep 12 '14 at 21:07
  • Yes it's added to the document, I just shortened the function. I 've edited it. – Michael Chourdakis Sep 12 '14 at 21:11
  • 2
    Ah. `scripts` added via `innerHTML` are not evaluated by the browser for security reasons (see https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML#Security_considerations). So your function really doesn't exist. See also [Can scripts be inserted with innerHTML?](http://stackoverflow.com/q/1197575/218196) – Felix Kling Sep 12 '14 at 21:12
  • May want to look into jsonp; see for example: http://stackoverflow.com/questions/6809053/simple-jquery-php-and-jsonp-example – psema4 Sep 12 '14 at 21:14
  • Don't do this please. –  Sep 12 '14 at 21:35

1 Answers1

0

Do this instead:

javascript:LoadContent('newstandby.php',foo)

since foo is a function and it is going to get called as a callback it is passed as function and not it is result( foo() )

Dalorzo
  • 19,834
  • 7
  • 55
  • 102