I am loading a .php file into a div I created.
I can successfully load the file into the div and everything works except javascript.
When i test the file in my browser, the javascript works, but not when it’s injected into my div.
index.php
<?php
$filename = $_GET["filename"];
if($filename != ""){
$fileData = file_get_contents($filename);
$fileData = trim($fileData);
$fileData = str_replace("\n", "", $fileData);
$fileData = str_replace("\r", "", $fileData);
echo $fileData;
die;
}?>
<body>
<script>
function LoadFile(filename, javascriptDiv){
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){
javascriptDiv.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?filename="+filename,true);
xmlhttp.send();
}
var javascriptDiv = document.createElement('div');
javascriptDiv.setAttribute('id', 'javascriptDiv');
javascriptDiv.style.position = 'absolute';
javascriptDiv.style.top = 50;
javascriptDiv.style.left = 50;
javascriptDiv.style.height = 200;
javascriptDiv.style.width = 300;
javascriptDiv.style.background = '#CCCCCC'; //so we can see that the DIV was created
LoadFile('http://127.0.0.1/Debug/test.php', javascriptDiv);
document.body.appendChild(javascriptDiv); //Display the Window
</script>
</body>
test.php <–the file i’m loading into the div
Plain text works
<?php echo "<br>php works <br>"; ?>
<a>html works</a><br>
<script>
function Test(){
alert('javascript works');
}
</script>
<input type="button" value="Test Javascript" onclick="Test()"/>
Here’s what it looks like on my site.
index.php
And here is a direct link to the test.php file
test.php
I need to get this working without altering the test.php file.
No, you can’t evaluate tags with lazy loading.
Generally speaking, I think the idea of allowing users to run custom javascript is a door open to exploits. I don’t know exactly what you are trying to achieve and why, but you’d better create a set of functions yourself and publish a simple public API (for example, to get a lightbox, add a ‘lightbox’ class to your element, or that kind of thing).
Alternatively, you could fetch the content of the tag and run an eval(). But again, it’s dangerous.
This page explains quite well the different methods you can use to achieve this. Of course, all assume you are running your own code and not some user code.