Increasing value in database after interval of time - javascript

i am working on a codeigniter project in which i am making a counter of every movie that is being clicked. Now i want if the user clicks the movie link the user is directed to the movie page and after 30 seconds the counter will be increased to 1. Currently the counter is increased on every click. Any Help???
Here is my view code
Watch in HD
Here is my controller code
public function watch_movie()
{
//$id = $_REQUEST['id'];
$id = $this->input->get('id');
$this->movie_counter->add_counter($id);
//$data['comment'] = $this->site_upload->fetch_comments($id);
//redirect ('site/play_movie', $result);
$this->load->view('Play_movie', $result);
}

Create a Queue!
Every click you insert into the queue, and another job (cronjob) insert every minute (smallest interval) the data from the queue in the correct table.

counter will be increased even every refresh too in this scenario, whateva you are saying for 30 sec interval ( you can use ajax request with a 30 sec timeout) but this seems like a buggy code what if some one closes it before 30 sec (browser) and you don't get any increment....
if you want to setup unique (views) use browser/ip/time based (for generic setup you can make it advance) and every time you get the request of counter addition check your db if you have same ip/browser and less duration as you say(30 sec or 1 min) then don't add other wise add 1 to script.

Related

How can set wait time in MySQL

Currently, I have a problem like this:
I add a new user to a table "users" with status set to "new". Then after 5 - 15 minutes the status is changed to "Em". It's dependent on how large the data is.
I would like to make a wait time in mySQL to get the status "Em".
how can I make a wait condition until it changes status, maybe in 5 minutes it has changed status already. how can I count those waits and get the status in every minute of waiting
You can guild me by Javascript it's okay.
Thank you so much
I am not entirely clear what your request is. But here I can provide you with some insight. If we need to trace the elapsed time since the creation of a new user and calculate how long it still needs for the new user to reach the em status, we can use a view. And if we want MySQL to update the status automatically when the time is right, we can use an event scheduler to check periodically.
-- Here is the view supposing it takes 600 seconds to reach em since creation
drop view if exists testview;
create view testview as select user_id,user_status,
concat(time_to_sec(now()) - time_to_sec(ts),' seconds have passed since adding the user.') as since_creation,
concat(time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()),' seconds more to reach em status.') as wait_time
from users
where user_status='new';
-- Here is the event scheduler which checks every 10 seconds
set global event_scheduler=on ;
delimiter //
drop event if exists periodic_check //
create event periodic_check on schedule every 10 second starts now() do
BEGIN
update users set user_status='em' where user_status='new'
and time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()) <=0;
END//

Real time data streaming should change UI based on last received time

I have real time data coming in, based on which I have to change indicator in UI. Meaning if I don't receive data in the last 30 sec , the indicator should turn red. If data is received before thirty 30 sec, it should be green. Note that data comes into the function one after the other. The indicator should change for each data(curveName) in this case.
I have used $timeout and $interval, but unable to crack the problem. Any help will be appreciated.
You can maybe add in your controller something like:
var timer,
timeLimit = 30000; //30s limit
function onDataReceived(data) {
// cancel previous timer
if(timer) $timeout.cancel(timer);
// assuming data is good set indicator to green
$scope.indicator = "green";
// set 30s timer for indicator to go red
timer = $timeout(function(){
$scope.indicator = "red";
}, timeLimit);
}
Depending on how the data is received and your application structure, you can consider using something like:
$scope.$watch('data', onDataReceived);

Keep track on time spent on each page when a particular user visit a page and keep a record in database

I am stuck with the an issue in which I have to track a time spend by user on particular page and save data in database using mongodb.
I have seen one answer about the same but I am confused where to add that piece of code as I am using angularjs. Do I have to keep this code in controller of that particular page or to the index where I am rendering all code using ui-view.
Code from How to measure a time spent on a page?
var start;
$(document).ready(function() {
start = Date.getTime();
$(window).unload(function() {
end = Date.getTime();
$.ajax({
url: "log.php",
data: {'timeSpent': end - start}
})
});
});
thnx in advance.
One simple way I can think of to do this is to calculate the total amount of time in seconds spent by the user on a particular page by using the $interval service of angularjs.
First, initialise a $scope variable for the total seconds spent,
$scope.TotalSeconds = 0;
Then, a function to increment the variable,
var IncrementTotalSeconds = function()
{
$scope.TotalSeconds += 1;
}
After that, use the $interval to increment the variable at every second.
$interval(IncrementTotalSeconds,1000);
Now you have the total seconds spent by the user on that particular page.
You can use the $scope.TotalSeconds to post the total time spent (in seconds) to the database.
Note: You can divide the Total Seconds if you want the time to be Minutes or Hours.

Penny Auction Timer Update after Database fetch

So i am implementing this feature in a penny auction website. Using countdown.js as the library to run a countdown.
the countdown works in a way that:
<div class="countdown cf content_item-countdown" style="width: 100%;" data-countdown="<?php echo date('M d, Y H:i:s O', strtotime($item['end_date']));?>"></div>
the end_date here, is from database, it is the date on which the timer will stop (and bidding will end)
the countdown function:
$('.countdown').each(function(){
var count = $(this), time = $(this).data('countdown'), format = $(this).data('format');
var Otime = new Date(time), o = {
serverSync: serverTime,
until:Otime,
// demo data set to reset timer, when it's finished
// change zeroCallback to prefered callback
zeroCallback: function(options) {
}
};
if(format){
$.extend(o,{format:format});
}else{
$.extend(o,{layout: '{dn} {dl} {hnn}{sep}{mnn}{sep}{snn}'});
}
$(this).countdown(o);
});
now i am supposed to implement another feature,
if the end_time <15 seconds (means the time remaining to bid is less than 15 seconds), and some one places a bid, the timer should automatically reset to 15 seconds, and so on. like: http://www.quibids.com/en/
i do this by updating the end_date to a certain seconds.
and updating timer:
$(time_update).html( '<div class="countdown cf content_item-countdown" style="width: 100%;" data-countdown="">'+data[$i].end_date+'</div>');
i assumed since the countdown timer is getting end_date it should automatically reset it.
But it doesn't, instead it prints the end date and reverts back to the old countdown.
the timer updates fine whenever i REFRESH the page, but i want it to refresh on the go, i assume it requires an AJAX call, any help?
the best way was to destroy the countdown widget and then display it using the updated end_date from database

How to code Websockets/AJAX for frequent database updates? Or is there a better method?

I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.

Categories