Refresh PHP Page using ajax - php

I have a php page that needs to be refreshed every 5 secs. On embedding the ajax file, I don't find the updates taking place in Firebug. Here is the skeleton of the code:
**notification.php**
<?php
....
....
?>
<html>
<head>
<script src="./refresh.js"></script>
<script type="text/javascript">
refreshContents();
</script>
</head>
<body>
....
<div id="identifier">
<p>Waiting area</p>
</div>
</body>
</html>
**refresh.js**
var seconds = 5;
var content = "identifier";
var url = "notification.php";
function refreshContents()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(f)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(g)
{
alert("Browser not supports Ajax");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4)
{
document.getElementById(content).innerHTML = xmlHttp.responseText;
setTimeout('refreshContents()', seconds*1000);
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
var seconds = 5;
window.onload = function startrefresh(){
setTimeout('refreshContents()', seconds*1000);
}

Though it may not be the ideal solution, jQuery has a pretty simple way of implementing exactly this:
$(document).ready(function () {
function reload() {
$("#content").load("notification.php");
}
setTimeOut(reload, seconds*1000)
}
I'm not sure that will work perfectly, haven't done it in a little while, but its a much more elegant solution I do believe.

Why not just put a <meta http-equiv="refresh" content="5"> tag into your <head>? It will refresh the page every 5 seconds without the need for any javascript.

see the following example :
<html>
<head>
<title>Refresh a page in jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<button id="PageRefresh">Refresh a Page in jQuery</button>
<script type="text/javascript">
$('#PageRefresh').click(function() {
location.reload();
});
</script>
</body>
</html>
this code definetly help you.
or we can use -
<meta http-equiv="refresh" content="5">

Related

Unable to show prompts or alerts using echo in php [duplicate]

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 5 years ago.
I tried to use a simple echo function with JS in it to show alerts and prompts, in a php page which is called using AJAX. I looked at lot of other SO posts, but couldn't find any working solution, like this one. Here is my code:
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
And
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
</body>
</html>
No need to echo the script out, just use it as html.
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
alert("Hello world! This is an Alert Box.")
</script>
</body>
</html>
Firstly, if you wish to put a script tag in an echo statement, it is possible. I think your problem is that you are running the code as a .html file instead of running it as a .php file. Just name the file something like file_loader.php
The code needs to run on a server. PHP is a server side scripting language.
Or you could copy and paste the code below into a php playground to quickly see it working.
<html>
<head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
<div id='debug'>Waiting for file to load.....</div>
<script>
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
</script>
</body>
</html>
Secondly, in order to load the file from the ajax code, you need to add an element that is identified by the specified Id - debug e.g.
<div id='debug'>Waiting for file to load.....</div>
Hope you find that helpful.

Ajax and setInterval() to auto update text file is not updating

I have two text files that are being display on a web page through ajax. I need these two files to update as soon as more text is added to the text file. When I completed this script I tested it on my localhost and all was working properly. Now I have attempted to get it to work on my web host and the text is displaying, but when it is time to update the files nothing updates.
I tried disabling the caching of the ajax response, but the files still do not update.
Here is the code:
<html>
<head>
<script>
$.ajaxSetup ({
cache: false
});
function UpdateDAU()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateD").innerHTML=xmlhttp.responseText.split('\n').join('<br/>';
}
}
xmlhttp.open("GET","../logs/dau.txt",true);
xmlhttp.send();
}
function UpdateFireBox()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateF").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","../logs/firebox.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script type="text/javascript">
UpdateDAU();
</script>
<div id="UpdateD">No Logs</div>
<script type="text/javascript">
setInterval("UpdateDAU", 1000);
</script>
<script type="text/javascript">
UpdateFireBox();
</script>
<div id="UpdateF">No Logs</div>
<script>
setInterval("UpdateFireBox", 1000);
</script>
</body>
</html>
Is there something that needs to be changed on the server or is this an issue with my code?What am I doing wrong?
After researching for the past week I finally have the display updating properly.
I could not get the files to update from the text file, so I had to echo the files from a php file before the ajax displayed it.
This is the code that is working on multiple machines:
<html>
<head>
<script>
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
function UpdateDAU()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateD").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","getdau.php",true);
xmlhttp.send();
setTimeout(function() {
UpdateDAU();
}, 1000)
}
function UpdateFireBox()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("UpdateF").innerHTML=xmlhttp.responseText.split('\n').join('<br/>');
}
}
xmlhttp.open("GET","getfirebox.php",true);
xmlhttp.send();
setTimeout(function() {
UpdateFireBox();
}, 1000)
}
</script>
</head>
<body>
<script type="text/javascript">
UpdateDAU();
</script>
<div id="UpdateD"><p class="text-warning">If there is no page...<br> Then the guards have not started there rounds.</p></div>
<script type="text/javascript">
UpdateFireBox();
</script>
<div id="UpdateF"><p class="text-warning">If there is no page...<br> Then the guards have not started there rounds.</p></div>
</body>
</html>
Here is the PHP files used to diplay files:
<?php
$file = file_get_contents('../logs/dau.txt', true);
echo $file;
?>
and second PHP file is the same:
<?php
$file = file_get_contents('../logs/firebox.txt', true);
echo $file;
?>
Using this code the logs inside txt files are updated and displayed every second without refreshing the page.
If there is a way to use these same steps but with only 1 php file instead of 2 show me and I will delete my answer and select yours.

php echod JavaScript won't run?

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.
reverse your string notation on the second echo statement that doesn't work.
change double quote to a single qoute like this
echo "<script type='text/javascript'>
...more stuff...
title: 'title text',
...more stufff...
";
to
echo '<script type="text/javascript">
...more stuff..
title: "title text",
...more stuff...
';
why this works is because double quotes will look for variables inside the string and single quotes doesn't. so when you have $(document) this inside of the double quote php thinks its a var
EDIT: since the echo statement is working
the use of innerHTML method doesn't evaluate scripts it only evaluates html tags.
so if you want the response to evaluate the in coming echo statement use the jQuery function append()
that being said change
document.getElementById(divid).innerHTML=xmlHttp.responseText;
to
$('#divid').append(xmlHttp.responseText);

DIV auto refresh

I try to refresh div every 5 sec but it doesn't work, I have 3 files.
index.php that contains:
<html>
<head>
<script type="text/javascript" src="javascript/jquery-1.3.2.js" ></script>
<script type="text/javascript" src="javascript/javascript.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval ("newmsg()", 5000);
setInterval ("newpause()", 5000);
});
</script>
</head>
<body>
<div id="msgs">
<?php echo date("H:i:s"); ?>
</div>
</body>
</html>
Then I have javascript.js that contains
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function newmsg(){
var request = GetXmlHttpObject();
request.open("get", "msgsprint.php", true);
request.send(null);
request.onreadystatechange = function response() {
if (request.readyState === 4) {
if(request.responseText != "false"){
$('#msgs').html(request.responseText);
}
}
}
}
function newpause(){
var request = GetXmlHttpObject();
request.open("get", "newpauseprint.php", true);
request.send(null);
request.onreadystatechange = function response() {
if (request.readyState === 4) {
if(request.responseText != "false"){
$('#newpauselist').html(request.responseText);
}
}
}
}
and i have msgsprint.php that contains
<?php
echo 'ivan';
?>
Could anybody please tell me what i did wrong.
There doesn't seem to be anything wrong in your code, maybe you are not getting a valid answer from msgsprint.php.
Here is a Demo based on your code that is working fine
I advise you to:
- you test the request status for an error.
- you use setTimeout to plan the next call to newmsgs
That's what i did in the demo.

Refreshing my php page with AJAX every 5 seconds

I'm creating a link-sharing website and on my index.php page (the page I want to refresh every 5 seconds) there are posts/links that must appear automatically (AJAX refreshing) without the user to refresh by him/herself or pressing F5 the whole time.
How would this work, precisely?
You should use the setInterval javascript function to deal with this issue.
setInterval(callServer, REFRESH_PERIOD_MILLIS);
See:
some info on ajax Periodic Refresh
javascript setInterval documentation
[edit] some good refresh examples, especially without js framework (depending wether you want to use jquery, mototools, another or no framework...)
you have to user the setInterval method to call your ajax function to inject new content into your div:
<HTML>
<HEAD>
<TITLE>Hello World Page</TITLE>
<script language="JavaScript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq.overrideMimeType) {
xmlHttpReq.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) { // IE
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttpReq) {
alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function() {
callBackFunction(xmlHttpReq);
};
xmlHttpReq.send("");
}
function callBackFunction(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var responceString = http_request.responseText;
//TODO implement your function e.g.
document.getElementById("myDiv").InnerHTML+ = (responceString);
} else {
alert('ERROR: AJAX request status = ' + http_request.status);
}
}
}
setInterval("xmlhttpPost('test.php')", 5000);
</script>
</HEAD>
<BODY>
Hello World
<div id="myDiv"></div>
</BODY>
</HTML>
Is there a need to use AJAX?
Unless I'm missing something; you could use the meta refresh tag:
<meta http-equiv="refresh" content="5">
I would recommend increasing the time between refreshes as this will put a heavier load on the server and may cause to freeze, or slow down the site.
Use setInterval(myAjaxCallbackfunction,[time in ms]).
Callback uses property of js that function are first class members(can be assigned to variables), and can be passed as argument to function for later use.

Categories