I have a JavaScript function that gets data and a function statement from PHP via XMLHttpRequest.How do I call the function that the PHP returned? It doesn't seem to exist. I'm totally lost as to how to make this happen. Here are test files that better explain it:
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function main(){
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/test2.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('foo=bar');
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById('testDiv').innerHTML = xhttp.responseText;
if (typeof injectedJS === "function") {
console.log('yes');
}else{
console.log("no");
}
}
};
};
</script>
</head>
<body onLoad=main()>
<div id="testDiv"></div>
</body>
</html>
test2.php
<?php
echo("<h1>Hello!</h1>");
echo("<script>function injectedJS() {var foo='bar';}</script>");
?>
The "Hello!" text is being displayed but "no" is logged to the console.
Thanks in advance for any help or a steer in the right direction, John