0

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.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Aditya
  • 395
  • 6
  • 18
  • This too convoluted: either fetch your remote script in original DOM via ``, or use [`jQuery.getScript`](http://api.jquery.com/jquery.getscript/) for instance. – moonwave99 Jan 25 '14 at 15:06
  • No I can't do it like that, my problem is much more complex but to keep things simple I have used a simple question to relate to my actual problem – Aditya Jan 25 '14 at 15:10
  • I need to find a solution of executing JavaScript code returned by a PHP file using AJAX – Aditya Jan 25 '14 at 15:13
  • Just return the data you need as JSON, and keep the .js sources clean without messing with PHP. – moonwave99 Jan 25 '14 at 15:20
  • can you give me an example on how to do this – Aditya Jan 25 '14 at 15:21
  • The whole web is full of examples, search for `json_encode()` [server side] and `jQuery.getJSON()` [client side] ^^ – moonwave99 Jan 25 '14 at 15:23

2 Answers2

1

BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/

If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.

E.G. a sample ajax.php

   if( isset($_GET['getscript']) ){
       header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
       echo 'alert("The script is working.")';

       exit;

   }

   echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
adrian7
  • 986
  • 12
  • 35
0

try this:

tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )

index.html:

<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">

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)
{
    var script = document.createElement('script');
    script.onload = function() {
    // alert("Script loaded and ready");
    };
    script.setAttribute("type","text/javascript");
    script.text = xmlhttp.responseText;
    document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html> 

in ajax.php try:

<?php
  echo 'alert("Hello World"); var testVAR = "Hello World";';
?>

if you want to run script from within a div:

use:

javaScript:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML);
}

and php:

<?php
  echo '<script language="javascript">
           alert("Hello World");
           var testVAR = "Hello World";
       </script>';
?>

hope it'll help you.

Vedant Terkar
  • 4,553
  • 8
  • 36
  • 62