So I’m new to Js & php and I’m trying to print out a piece of code from a call back function
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","callback_json.php",true);
xmlhttp.send();
}
</script>
<title>Simple Cross Domain Ajax</title>
</head>
<body>
<h1>.....</h1>
<h2>.....</h2>
<button onclick="loadXMLDoc();">Get Data</button>
<div id="myDiv"><h2>...</h2></div>
</body>
</html>
and my php file goes like
<?php
$ch = curl_init();
$url='someurl';
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo "<script type='text/javascript' src='syntaxhighlighter/scripts/shCore.js'></script><script type='text/javascript' src='syntaxhighlighter/scripts/shBrushJava.js'></script><link href='syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css' /><link href='syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css' />";
echo "<pre class='brush:java;'>";
echo $data;
echo "</pre>";
echo '<script type="text/javascript">SyntaxHighlighter.highlight();</script>';
?>
And it seems syntax highlighter works on my php file but not after call back…I did some research and I know I’m supposed to use SyntaxHighlighter.highlight() instead of all() in the code but I’ve already done that. Is there any problem with my code structure?
<script>tags added by innerHTML are not executed by the browser. You need to execute them manually:Alternatively you can re-append the script nodes to the page instead of evaling it:
but this is exactly the same as evaling the code anyway (no really, think hard about it both methods execute the code unchecked).
A better way is to avoid script injection altogether by adding the Syntaxhighlighter files at the top of the page and calling
SyntaxHighlighter.highlight()after you’ve innerHTMLed the code.