i would like to ask how can i make a php script which echoes the id of the data stored in a database repeat itself after specific time for example after 2 minutes.i don't want to use a cron job or another scheduler.Just php or javascript implemantation.Thanks in advance..
I've done similar with this script. While the user is on the page, it runs scriptToRun.php every 2 minutes.
function changeFeedAddress() {
$.ajax({
type: 'get',
url: 'scriptToRun.php',
success: function(txt) {
// do something with the new RSS feed ID here
}
});
}
setInterval(changeFeedAddress,120000); // 2 MINUTES
Alternate to #JMC Creative (Self-contained for example's sake):
<?php
// check if the $.post below is calling this script
if (isset($_POST['ajax']))
{
// $data = /*Retrieve the id in the database*/;
// ---vvvv---remove---vvvv---
// Example Data for test purposes
$data = rand(1,9999);
// End Example Data
// ---^^^^---remove---^^^^---
// output the new ID to the page so the $.post can see it
echo $data;
exit; // and stop processing
}
?>
<html>
<head>
<title>Demo Update</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// assign a timeout for this script
var timeout = 2 * 60000; // 2 minutes
// create a function we can call over and over to fetch the ID
function updateDBValue(){
// call this same script and retrieve an "id from the database" (see top of page)
$.post('<?php echo $_SERVER['PHP_SELF']; ?>',{ajax:true},function(data){
// 'data' now contains the new ID. For example's sake, place the value
// in to an input field (as shown below)
$('#db-value').val(data);
// set a timer to re-call this function again
setTimeout(updateDBValue,timeout);
});
}
// call the function initially
updateDBValue();
});
</script>
</head>
<body style="text-align:center;">
<div style="margin: 0 auto;border:1px solid #000;display:block;width:150px;height:50px;">
DB Value:<br />
<input type="text" id="db-value" style="text-align:center;" />
</div>
</body>
</head>
Why not just do this?
<?php
header('refresh: 600; url=http://www.yourhost.com/yourscript.php');
//script here
?>
If your generating your ID at random from within the script...this will work fine. The page will refresh itself every 10 minutes.
Related
I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>
I have some problems with understanding of ajax use.
Let's say I have file like this (this is just a pseudo code, dont look at the basic mistakes right now please) I have read so many articles, but i find them so hard to understand
///////////////// file 1 /////////////////
<?php
x = 1;
<button onclick=somefunction(x)></button>
?>
<script>
//here goes some ajax code sending this x variable to another php file
</script>
Lets say it looks like this
////////////// file 2 ////////////////
<?php
/get x variable + sendint it back
return x=2
?>
Now what i want to do is to make this x value come back to the first script and make x=2. How do i do this?
Here is an example using JQuery with some notes to try to describe what happens.
<html>
<!--file: ajax_basic.php-->
<head>
<title>Ajax Basic Example</title>
</head>
<body>
<input type="text" id="example_input" value="1">
<button id="example_button">Example</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// .click(function() executes an anonymous function when the button is clicked
$('#example_button').click(function() {
// get the current value from the input
test_value = $('#example_input').val();
// $.get is the AJAX method.
// It sends the object {'sent_value': test_value} to test.php
// function(response) is the the function that will be executed when
// a response is returned from the test.php
$.get('test.php', {'sent_value': test_value}, function(response) {
// here, x is taken from the response of the php script.
// You can do whatever you like with this value.
x = response.returned_value;
// for this example, it updates the value of the text input
$('#example_input').val(x);
}, 'json');
});
});
</script>
</body>
</html>
This is the PHP file that will handle the request. All it does for this example is increment the value it receives and return the new value.
<?php
// file: test.php
$response = array('returned_value' => $_GET['sent_value'] + 1);
echo json_encode($response);
If you are using jQuery, you should switch from onclick=somefunction(x) to a jQuery binding, ie. .on()/.click()/etc. see https://stackoverflow.com/a/826697/689579
Using jQuery you could do something like-
<?php $x=1;>
<button id="mybutton">MyButton</button>
<script>
var x = <?php echo $x; ?>; // set initial x value to php value
$(function(){
$('#mybutton').click(somefunction);
});
function somefunction(){
$.ajax({
url: 'phppage.php',
data: {number:x}, // send current x value
...
success: function(result){
x = result; // when php file returns 2 (or other value increase x
}
});
}
</script>
I use php to fetch some information from database and I want to display a progress bar until my php executes and I need to display my page after the php execution. how can I achieve this.
Excatly like how the gmail loads the inbox
Have look at https://github.com/TheBrockEllis/jQuery-and-PHP-Progress-Bar
and also http://www.johnboy.com/blog/a-better-php-upload-progress-bar-using-jquery
It is fairly simple to do.
From the description I don't know how in depth this progress bar needs to be. This is pseudo code that should get you started. It won't run AS IS... you will need to make these functions do something.
EXAMPLE 1: 100% client side checker
<script type="text/javascript">
/* in document head */
var section1 = 0;
var section2 = 0;
var section3 = 0;
var section4 = 0;
//lightbox w/ progress meter
showProgressLightBox();
//async ajax calls here to load the various sectoins
loadPage(); // not a real function
function displayProgressMeter()
{
var count = 0;
if (section1) count++;
if (section2) count++;
if (section3) count++;
if (section4) count++;
if (count != 4) {
displayProgress(count); //will repaint lightbox progress meter
//based on X of Y sections loaded
setTimeout('displayProgressMeter()',500);
}
else
{
closeLightBox(); //page is loaded
}
}
displayProgressMeter(); //start the event
//note my ajax calls will flip the values of the various variables we are checking
</script>
Example 2 server checker. I have something like this running for a project that takes about 30 minutes to run a certain activity. The progress itself is updated by updating mysql from a cron scheduled task
First I have a PHP file called "batchStatusChecker" which looks something like this:
<?php
define('AREA',"COLREPORT");
include(__DIR__."/../phoenix/includes/config.php");
session_start();
$batch=(int)#$_REQUEST["batch"];
include (__DIR__."/affiliateUploadClass.php");
$rs=Query("select commitMessage from phx_AffiliateUsersFiles where ID=$batch;");
echo json_encode(array("info" => $rs->Get("commitMessage")));
?>
Then I have some javascript that updates a div with the current status or shows a completion message. You could adapt a technique like this to your needs if it is more appropriate for your use case
function checkStatusOfReport()
{
$.post("/affiliateUpload/batchStatusChecker.php", { "batch": <? echo $batch; ?> },
function(data)
{
if (data.error)
{
$("#ErrorInformation").html(data.error);
$("#UploadInformation").remove();
}
else
{
var msg="<h3>" + data.info + "</h3>";
$("#UploadInformation").html(msg);
if (data.info == 'COMPLETE')
$("#UploadInformation").html('<h3>The import of this batch is completed.</h3>');
else
setTimeout("checkStatusOfReport()",4000);
}
}, "json");
}
checkStatusOfReport();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// Total processes
$total = 2;
// Loop through process
for($i=1; $i<=$total; $i++){
// Calculate the percentation
$percent = intval($i/$total * 100)."%";
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> </div>";
document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
// Sleep one second so we can see the delay
sleep(1);
}
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
</html>
Consider an AJAX call that writes to a div:
recent_req=$.post('result.php', { d: data }, function(returnData) {
$('#content').html(returnData);
});
The PHP script at result.php performs some functions that take time, about 5-20 seconds per step. I am using PHP's flush() function to get the info to the browser as soon as each step starts and ends, but how can I get the Javascript to write the data to the #content div as it comes in?
Thanks.
EDIT:
To clarify: Assume result.php looks like the following and due to constraints cannot be practically refactored:
<?php
echo "Starting...<br />";
flush();
longOperation();
echo "Done with first long operation.<br />";
flush();
anotherLongOperation();
echo "Done with another long operation.<br />";
flush();
?>
How might the AJAX be structured to call result.php such that the echo statements are appended to the #content div as they come in? Any solution with / without jQuery is welcome. Thanks!
There's a technique using an iframe which you could use to achieve this.
Similar to other suggestions involving frames but it doesn't involve sessions or polling or anything, and doesn't need you to display the iframe itself. It also has the benefit of running any code you want at any point in the process, in case you're doing something more sophisticated with your UI than just pushing text to a div (e.g. you could update a progress bar).
Basically, submit the form to a hidden iFrame then flush javascript to that frame, which interacts with functions in the iFrame's parent.
Like this:
HTML:
<form target="results" action="result.php" method="post">
<!-- your form -->
<input type="submit" value="Go" />
</form>
<iframe name="results" id="results" width="0" height="0" />
<div id="progress"></div>
Javascript, in your main page:
function updateProgress(progress) {
$("#progress").append("<div>" + progress + "</div>");
}
result.php:
<?php
echo "<script language='javascript'>parent.updateProgress('Starting...');</script>";
flush();
longOperation();
echo "<script language='javascript'>parent.updateProgress('Done with first long operation.');</script>";
flush();
anotherLongOperation();
echo "<script language='javascript'>parent.updateProgress('Done with another long operation.');</script>";
flush();
?>
You cannot 'stream' data using regular ajax calls, for you can't make your user's browser 'listen' to server requests. Your 'success' function will only be called when data's done processing.
There's, though, much discussion on 'Ajax Push' on the internet and apparently HTML5 has websocket objects that can be used to make your user's browser listen to server requests. The syntax definition is not quite stable yet, so you don't want to mess with it, as it may change soon.
What you may want to do is dispatch a request for step1, wait for its return and then dispatch a request for step2. It'll add some overhead to your overall processing time (and will make it much more verbose), but it should work fine if you only have a few big steps. If your steps don't take too much processing, you shouldn't do it (as the communication time will become greater than your 'effective processing time').
EDIT: What you can also do is write the progress on the user's session, for example. That way, you can periodically ping the server with a request for an update on the status. This way, even if you have many small steps, you'll only have to dispatch requests every 10 seconds or so, that being an improvement over dispatching for every step.
As an alternative solution, you could submit a hidden form into an iframe, as shown in the following example:
<?php
function output_data($data) {
echo str_pad($data, 4096, ' ', STR_PAD_RIGHT) . "\n";
flush();
}
function long_runner() {
output_data("");
output_data(date("H:i:s").' - Starting...<br />');
sleep(10);
output_data(date("H:i:s").' - Done with first long operation.<br />');
sleep(10);
output_data(date("H:i:s").' - Done with another long operation.<br />');
return("<script>parent.task_complete()</script>");
}
if (isset($_REQUEST["status"])) {
die(long_runner());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Write to IFRAME as data streams in</title>
<style>
#myform { display: none }
#frm { width: 50% }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function task_complete() {
alert('Task completed');
}
$(document).ready(function() {
$('#starter').click(function() {
$('#myform').submit();
});
});
</script>
</head>
<body>
<form id="myform" method="get" target="frm" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
<input type="hidden" name="status" value="0">
</form>
Start<br />
<iframe id="frm" name="frm" frameborder="0"></iframe>
</body>
</html>
Writing a dynamic data stream to a div:
Here goes.. you asked specifically how to dynamically write data streams to a "div". As many have said it is possible to write dynamically to an iframe and we just need to go one step further. Here is a complete solution to your issue, which will bring that data back to your div with a maximum delay of .5 seconds. It can be adapted if you need a more prompt update.
<!DOCTYPE html>
<html>
<head>
<title>dynamic listener</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var count;
$(function(){
$('#formx').submit(function(){
setTimeout(function(){ check_div(); }, 500);
count = 0;
return true;
});
});
function check_div()
{
var $iframetxt = $('#iframex').contents().text();
var $div = $('#dynamic');
if( $iframetxt != $div.text() )
{
console.log('rewritten!');
$div.text( $iframetxt );
setTimeout(function(){ check_div(); }, 500);
count = 0;
}
else
{
count++;
if(count < 40) setTimeout(function(){ check_div(); }, 500);
else console.log('timed out');
}
}
</script>
</head>
<body>
<div>
Form
<form id="formx" action="result.php" method="post" target="iframex">
<input type="submit" />
</form>
</div>
<div id="dynamic"></div>
<iframe id='iframex' name="iframex" style="display:none" ></iframe>
</body>
</html>
1. On form submit, the streaming data is sent to the iframe.
For this we just set the target attribute in the form tag to the iframe name.
2. check_div() runs every .5 seconds to compare the text of #dynamic div to the text contents of the iframe.
If there is a difference between them, the data is written to the div and the timeout is called again. If there is no difference, the timeout counter increments. If the count is less than 40 (40 x .5 sec = 20 seconds), it calls the timeout again. If not, we assume the stream has completed.
Here is a solution using polling with a session:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var pollTimeout;
function pollResult(){
$.get('poll.php', function(response) {
// Update #content with partial response
$('#content').html(response);
pollTimeout = setTimeout(pollResult, 1000);
});
}
$.post('result.php', function(response) {
// Result is loaded, stop polling and update content with final response
clearTimeout(pollTimeout);
$('#content').html(response);
});
// Start polling
pollResult();
</script>
</body>
</html>
Result PHP:
<?php
class SemiStream{
public function __construct(){
#session_start();
$_SESSION['semi_stream'] = '';
}
public function write($data){
#session_start();
$_SESSION['semi_stream'] .= $data;
// We have to save and close the session to be
// able to read the contents of it in poll.php
session_write_close();
}
public function close(){
echo $_SESSION['semi_stream'];
unset($_SESSION['semi_stream']);
}
}
$stream = new SemiStream();
$stream->write("Starting...<br />");
sleep(3);
$stream->write("Done with first long operation.<br />");
sleep(3);
$stream->write("Done with another long operation.<br />");
$stream->close();
echo 'Done.';
Poll PHP:
<?php
session_start();
echo $_SESSION['semi_stream'];
This works, without the use of PHP's output buffering.
Check out the Pusher service, seems like it could do exactly what you want: http://pusher.com/
Probably, the question is about how to implement Push technology in your app. I would suggest you to look this question which has great answer with example
I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>