I have a problem where when I echo JavaScript from a PHP page to a HTML page using AJAX it won't run however, when I Inspect Element the JavaScript is there, I also echo some text and the text does show.
When I add the JavaScript manually in the HTML it works perfectly and the PHP, HTML and AJAX files are all in the same directory so there is no problem there.
I have 3 pages index.html, boo.php and ajax.js
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/jquery.gritter.css" />
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('jquery', '1.7.1');</script>
<script type="text/javascript" src="js/jquery.gritter.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<script type="text/javascript"><!--
refreshdiv();
// --></script>
<div id="timediv"></div>
</body>
</html>
boo.php
<?php
// Fetch the data
$query = "SELECT * FROM $tablename";
$result = mysql_query($query);
// Return the results, loop through them and echo
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$name = $row['name']; // this equals Admin
if($name == 'Admin') {
echo $name; // this echos Admin and shows on index.html
// the javascript below doesnt
echo "
<script type='text/javascript'>
$(function(){
$(document).ready( function () {
var unique_id = $.gritter.add({
title: 'title text',
text: 'description text',
image: 'icon.jpg',
sticky: true,
time: '',
class_name: 'my-sticky-class'
});
return false;
});
});
</script>
";
}
}
?>
ajax.js
// Customise those settings
var seconds = 5;
var divid = "timediv";
var url = "boo.php";
////////////////////////////////
//
// Refreshing the DIV
//
////////////////////////////////
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
What the script is suppose to do check every 5 seconds if there is if there is a username in the database called Admin then show a gritter notification if there is.
Any ideas what I can do? thanks.