Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS()
, following is the content of the function exJS()
var xmlhttp;
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=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php
is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS()
the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv"
I see that the entire script is embedded inside the div
but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR
, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div
element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php
file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx()
the JavaScript code gets inserted into myDiv
but nothing happens, no alert.