i want to make some changes for my site,but i don't know how;
and i will be glad if you could help me with that,
if its possible to see really online the seconds counting until zero,not only the time has left
and second, if i want that the countdown will start automatically to count again and start from the begining by a loop.
here is the code that I want to insert my changes
<?php
//You must call the function session_start() before
//you attempt to work with sessions in PHP!
session_start();
//Check to see if our countdown session
//variable has been initialized.
if(!isset($_SESSION['countdown'])){
//Set the countdown to 120 seconds.
$_SESSION['countdown'] = 120;
//Store the timestamp of when the countdown began.
$_SESSION['time_started'] = time();
}
//Get the current timestamp.
$now = time();
//Calculate how many seconds have passed since
//the countdown began.
$timeSince = $now - $_SESSION['time_started'];
//How many seconds are remaining?
$remainingSeconds = abs($_SESSION['countdown'] - $timeSince);
//Print out the countdown.
echo "There are $remainingSeconds seconds remaining.";
//Check if the countdown has finished.
if($remainingSeconds < 1){
//Finished! Do something.
}
PHP is a server side scripting language and it stands for Preprocessor Hyper Text (Personal Home Page before that).
What PHP does is not what you want to do with it if you catch my drift.
PHP takes dynamic code e.g. records from a database and generates the HTML that goes with it (often you have to create loops for products etc...)
When PHP is done it sends the response to the browser and is done processing from there.
You want to add a counter that works live on the page itself.
This is a different story.
You'll need to write some JS (JavaScript) on page load that will count down from where the counter was when the page first loaded.
You could make a script in JS that takes a given timestamp and counts down from there.
Each time you load a new page with the JS doing its thing onload will make sure the counter will count down until it hits 0.
I would love to help you further but I'm # work at this moment so all I can do is point you into the right direction.
What I think you want to do:
get timestamp from PHP and insert it into a div
load JS on pageload
fetch the hidden div timestamp
countdown dynamicly from the timestamp using js
And one last thing (seeing as you don't seem to have alot of experience with php / js) - instead of using jQuery, further complicating things for a very small puny task I would look up a plain JS example of what you are trying to do and learn from there.
using jQuery for just this is waaaaay overkill and not needed at all - adding 90kb code for a silly clock that is ;)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been searching everywhere for a method of streaming a text file. By streaming I mean I want the page to remember its location, and everytime a new entry is added, it will add it to the bottom.
Example
(Displayed on page from txt file)
Jack
John
Ellis
(text file is updated to)
Jack
John
Ellis
Emma
Carly
I want the page to pick up the changes without having to refresh the whole page.
Im learning alot. I have figured out how to display the text files on the page via php (my knowledge base is stuck with php/html only self taught). I can get it to refresh, but im having to use javascript to auto scroll down the page to the bottom everytime, and have the page refreshing every few seconds.
Any ideas or tips?
Well, I would not do this the Shrek's Donkey way:
Are we there, yet?", 5 seconds later, "Are we there, yet?
What is the problem with this?
Bandwidth consumption, pure and simply.
What should I do?
The answer is: Server Push. Or something like Server Push, since is not possible to start things from the server with HTTP.
Instead of poll the server every 5 seconds if there is a new version of the file, why not let the server notify you just when it really has changed?
And how do I do this?
The answer is: with Ajax, but with a different approach.
The high level algorithm is:
Send an Ajax request to the server from the browser.
When the server receives the request, verify if the file has changed.
If it has changed, then return the new data.
If not, make the server sleep for a while and then go back to step 2.
If a long time has passed and there is no modification, the server could (or must) return a response, with no data bounded to it.
How can I check if the file has changed?
Instead of reading the file and comparing the data, a better approach is to send with the request the timestamp of when the file had it last change. You can do this with the filemtime funciton.
On the server, you verify if the file last modified time is bigger than the one coming from the request. If it is, then you read the file and send the response along with the new file modified time (step 2a). If not, go for step 2b and use the usleep function to make the server sleep for a while and save CPU.
To know if a long time has passed and there's no change, you can use the microtime function at the beginning of the script and make the difference of its value on every iteration. If there has been past much time, you'll send an empty response.
Making a draft, the server-side script would be like:
$startTime = microtime();
$filePath = '/path/to/file.txt';
$lastModifiedTime = $_GET['lastModifiedTyme']; // Supposing it comes from the query string
$currentModifiedTime = null;
while ($currentModifiedTime = filemtime($filePath) < $lastModifiedTime) {
usleep(1000); // dorme por 1 seg.
// If has passed more than 1 minute
if ((microtime() - $startTime) > 60000) {
header('HTTP/1.1 304 Not Modified'); // Or simply http_response_code(304) for PHP 5.4+
exit;
}
}
$data = file_get_contents($file);
$jsonResponse = json_encode(array(
'data' => $data,
'modifiedTime' => $currentModifiedTime
);
echo $jsonResponse;
On the client side, you'll have to re-run the request every time you receive a response. This could (and should) have a litte delay.
It sounds like a kind of an overhead, I know, but just for you to know that there are another ways of doing this.
What I'd recommend you do is use AJAX to periodically call a PHP file which loads the text file and update your web content to display the new content.
It will be similar to this: Refresh a table with jQuery/Ajax every 5 seconds
For a school project we have to build a web app. I'll be creating something where people can keep track of their classes, their homework, and their free time. A planner/calendar. (I'm making it sound really lame here but hey, I'm tired and English isn't my first language ;) )
I'll be working in CodeIgniter for the PHP logic, combined with the usual.. CSS, jQuery, mySQL. PHP is a requirement for the course; I chose to do this in CI because well.. I wanted to learn the framework. We kind of have to show off what we can do at this point of our 'school career'.
Anyway, I would like to ask for some insights regarding a feature I want to implement. At the top of my page, I would like to show a bar which contains the days of the month. Below the day number, I would be showing how many tasks are added on that day by means of some dots. When the user clicks previous or next, I want to show the previous/next month's days. I also want some sort of slider underneath this box which the user can use to slide left and right, and cycle through the days that way. I hope that made sense?
EDIT 2: I want the slider to be dynamic. If the user slides to the previous or next months, or clicks the buttons, I want it to load the days of the previous/next months and show those. Also, say we're at the 26th of a month, the slider would have to show something like 10-31 of this month AND 1-10 of the next month. I suppose I'll also have to change my month indication (not like in the image here) so a user knows when another month starts (I'll show them the name of the month).
Here's a picture (don't mind the day numbers being messed up, I was lazy doing that correctly in Photoshop. will fix that tomo):
I've been looking at the jQuery UI sliders. I suppose I'd have to grab the number of days from a database or by using PHP? I guess the cal_days_in_month function could come in handy here. When the user clicks on the arrows or slides left or right, I don't want the page to refresh. Should I go with ajax calls there? I'm not quite sure how to implement this, to be honest. The numbers are also links to a calendar type of view which shows underneath this bar.
Could I possibly use the CI Calendar class for this? Or is it more for full-fledged google calendar-type of calendars? I thought this screencast could perhaps be useful?
If possible, could someone please provide some insights on how to start working on this and which plugins/etc I could perhaps use? I'm not sure where to start, to be honest. I'm sure I can work this out somehow, but I guess it'd be nice to get a kickstart by means of some help here. The main problem I'm seeing is the slider/next/previous thing and loading in the previous/next month's days.
Thanks in advance.
EDIT: I realise some people might say/think 'OMG, why don't you just use the skills you have instead of trying something you have to ask us about!'. Well, this is because I actually want to learn something while doing this project. Keep in mind, I'm not asking for lines of code here, I'm just asking for some insight on where to start and what stuff to use; perhaps little snippets that can help me out. Thanks.
UPDATE:
I got a very basic 'day bar' working. Still without a slider, nor do the previous and next buttons work, but hey.. at least it fills it in dynamically. It shows the 5 days previous to the current day, then this month till the end. Whatever is left to fill in gets filled with days of the next month. Quite basic. However, I do have a couple of questions!
Since someone told me yesterday that I was breaking design patterns by doing some stuff the way I was doing it, I'm extremely paranoid about the way I'm working now and I would really like some feedback from 'CodeIgniter pro's'. To fill in the 'day bar', I created a helper with a couple of methods. (One method to dynamically fill that 'month year' thing you see in the picture, another method init() which loads the list of the days, like I explained before). I loaded this helper in the controller and I'm now using the methods in my view:
<ul>
<?php
init($current_day_of_month, $current_month,
$current_year, $days_in_current_month, $show_history);
?>
</ul>
The helper then echoes my day values in my view. Is this good or bad practice? I kept thinking the wrong way when I wanted to start writing the code for this.. I wanted to have a function somewhere in my controller and then call it from the view, but I read that I shouldn't be doing it like that.. that I had to reverse my logic. I find it hard to wrap my head around the fact that I have to do this by sending arrays of data to my view (from my controller), so I opted for creating the helper. Good? Bad? Any tips, resources I should read, screencasts I should watch? Thanks a bunch.
This seems pretty straight forward to me. I don't really have time to write the whole thing now. but heres what steps I would take.
1) create a model which gets all the tasks for a month, and uses that to create an array of {date}=>{num_tasks} e.g. {'1'=>3,'2'=>1, "3"=>0, ...}. //hint: use a regular SQL count OR just loop thru and tally them.
2) create a controller function to return this array as JSON. Something like this:
public function get_month($month, $year) {
$tasks = $this->task_model->get_each_days_taskcount($month, $year);
$json = json_encode ($tasks);
echo $json;
}
3) write a html page which has a javascript function to call this controller function with AJAX. Something like:
function fill_calendar(month, year) {
$.get('some_controller/get_month/' + month + '/' + year, function(data) {
// parse the JSON then
// do something with the data here like $('#calendar').append();
});
}
4) Load this month with something like this:
$(function() {
var d = new Date();
var tmonth = d.getMonth();
var tyear = d.getFullYear();
fill_calendar(tmonth, tyear); // populate with this month
});
5) make the prev and next buttons work with something like
$('#prev_button').click(function() {
fill_calendar(current_month - 1 , tyear);
// you will probly need to make this calculation smarter than just minus 1
});
The key thing if you want your system to be dynamic is to make the data transmission short. So using Ajax, as icchanobot says, send the request for a specific month. Use get:
'some_controller?m=' + month + '&y=' + year
or even:
'some_controller?next' // or previous
The controller has to get data for the correct month, but not send back the whole month - only the data needed for your display, in a format as tight as possible. You could query how many events run on which days of that month:
SELECT day, count(event)
FROM event_table
WHERE DATE BETWEEN 'yyyy-mm-01' AND 'yyyy-mm-31'
GROUP BY day
ORDER BY day;
query needs adapting to your data structure - use a function to get the day from a complete date, and maybe use indexes so that the query returns the data fast.
Then the controller returns a string as short as you can make it, of the relevant data sorted in day order:
1=3,15=1,29=2
That would mean "1st=3 events, 15th=1 event, 29=2 events". If you don't want the number of events then "1,15,2" is enough. Empty days aren't transmitted.
the data is received by an ajax event handler on your web page and you parse it by using split, then populate the slider by using a loop.
Your biggest drag, in a very dynamic application, is if it slows down when you repeatedly ask for the next month and the next.
A few tricks:
Update the display while waiting for data; you send your query, and while it is being processed, you can slide the month into view, with the correct number of days, looking disabled so that the user knows immediately that they will get their data, and that it is in progress. Then when the data comes, populate and highlight. It will feel instant though it isn't.
Avoid processing information the user doesn't want anymore. If somebody clicks "next" three times, they want the data for july, not may, june and july. Don't process what you don't display.
Cache data you've already asked, unless you want the system to return dynamically to the server for the latest state of the calendar. You've asked for the data for May and June, but not displayed it; when the user hits "back", don't ask for that data again.
Good luck!
I really don't see the complication about this.......
If you just use the jQuery UI DataPicker and modify the js file so it stores the days in a slider, then put the data in a jQuery UI Slider and you should have almost what you require.
I've got a script in php that continually grows an array as it's results are updated. It executes for a very long time on purpose as it needs to filter a few million strings.
As it loops through results it prints out strings and fills up the page until the scroll bar is super tiny. Instead of printing out the strings, I want to just show the number of successful results dynamically as the php script continues. I did echo(count($array)); and found the number at 1,232,907... 1,233,192 ... 1,234,874 and so forth printed out on many lines.
So, how do I display this increasing php variable as a single growing number on my webpage with Javascript?
Have your PHP script store that number somewhere, then use AJAX to retrieve it every so often.
You need to find a way to interface with the process, to get the current state out of it. Your script needs to export the status periodically, e.g. by writing it to a database.
The easiest way is to write the status to a text file every so often and poll this text file periodically using AJAX.
You can use the Forever Frame technique. Basically, you have a main page containing an iframe. The iframe loads gradually, intermittently adding an additional script tag. Each script tag modifies the content of the parent page.
There is a complete guide available.
That said, there are many good reasons to consider doing more pre-computation (e.g. in a cron job) to avoid doing the actual work during the request.
This isn't what you're looking for (I'm as interested in an answer to this..), but a solution that I've found works is to keep track of the count server-side, and only print every 1000/5000/whatever number works best, rather than one-by-one.
I'd suggest that you have a PHP script that returns the value in JSON format. Then in another php page you can do an AJAX call to the page and fetch the JSON value and display it. Your AJAX call can be programmed to run perhaps every 5 seconds or so depending on how fast your numbers output. Iframe though easier, is a bit outdated.
I'm in charge of a printer, so I wrote a script which runs every 5 minutes and figures out if the printer has paper. If it doesn't, the script will text me. The problem is, if I'm busy, and can't fill the printer, I don't want the script to continue to text me every 5 minutes. Is there a way I can force it to only send me at most 1 text every 8 hours or so, to ensure that the script doesn't text me twice for the same out-of-paper situation? The only thing I can currently think of is to create a db of times that I get texts, then make sure that the most recent one wasn't too long ago, or to create a local file with the most recent time in it.
Thanks!
You need to store somewhere the fact that it has text you and when this last occurred. You could do this using a plain file and by reading the files modification date to see when the text was last sent or you can use a database.
Assuming that the script that sends the SMS is PHP, use something like this.
Can probably find a cleaner way of doing this, but this is just to show you the logic that is needed.
<?
/*
* Replace outOfPaper() / sendSms() with the actual logic of your script
*/
$statusFile = './lastsms';
if(outOfPaper() && (is_file($statusFile) && (filemtime($statusFile) < time()-((8*60)*60)))){
sendSms('+4412345678','Printer out of paper');
touch($statusFile);
}
?>
I have page where where I list all comments for a post. Next to each comment I have a time value in full format including the date/time (2010-01-02 11:11:20).
I know that I can format it in PHP before displaying it, so it shows;
posted 40 secs ago
posted 5 days ago
but that would not be efficient as I am going to cache the page once it is generated.
On SO I see that they have some kind of java script for showing it, so it is run on the browser of the client:
alt text http://img528.imageshack.us/img528/5442/35118769.png
So basically I need a java script that runs on the browser that would instead of showing my date/time show "posted 4 hours ago". All help is welcome.
Sounds you want this: timeago: a jQuery plugin.
Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
I quote further:
Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
You can take full advantage of page caching in your web applications, because the timestamps aren't calculated on the server.
So it should fit your needs.
You can put the "timestamp" of the page into the page when you render it. This is the fixed time that doesn't change. Look at PHP's time function for this (http://www.php.net/manual/en/function.time.php). It gives you seconds since the UNIX epoch started.
Then, when the page is running, use Javascript's Date object. It encapsulates something similar. Do a getTime() on a new Javascript Date object, which will get you also seconds since the UNIX epoch.
Subtract one from the other to get the elapsed time between then and now, and do whatever pretty formatting you need to make it display right in your page.
Edit: See also Felix's answer about timeago, which is a nifty tool to do the second half of this process for you automatically.
Output your date in a format accepted by the parseDate method or as a constructor parameter for date. Place them in some nodes which can later on easily be grabbed by a javascript framework (or your own methods) and then perform some time/datediff methods on these grabbed values and replace the node's content.