jQuery - Animate & Time interval - php

<script>
$(document).ready(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
});
</script>
Database.php:
<?php
$xp = 50;
$level = 100;
$xp_percent = $xp * 100 / $level;
echo $xp_percent;
?>
What i'm trying to do, is that if $xp_percent increases in database.php, then #exp_bg's width will animate into desired width without refresh.
I tried to do that with time interval, which takes data from database.php every speciefed interval of time, but i failed doing that.
Could anyone help me with that?

Your probably going to have to put it inside a setTimeout function like so:
var refreshId = setInterval(function() {
$.get("database.php", function(data){
var xp = data + "%";
$('#exp_bg').animate({
width: xp
}, 1500, function() { });
});
}, 1000);
This would check every second.

Related

Run jQuery Counter with value from MySQL

I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.
Counter Function Code:
Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.
<script type="text/javascript">
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: 99950,
to: 100000,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
</script>
HTML Code:
<h2><span class="timer" style="color:#F44336;font-weight:700; font-size:20px;"></span></h2>
You will need a server side language for getting data extracted from mysql. Say for instance, if you are using PHP as your server side language, in that case you can simply put :
<?php
mysql_connect('host','username','password') or die();
mysql_select_db('your_database_name') or die();
$query='SELECT `min_count`, `max_count` FROM 'your_table_name`;
$row=mysql_query($query);
while($rs=mysql_fetch_array($row)){
$from=$rs[0];
$to=$rs[1];
}
?>
<script type="text/javascript">
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: <?php echo "$from"; ?>,
to: <?php echo "$to"; ?>,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
Do you mean, you want to get an sql query to the counter?
You could use AJAX for that, make a php file with an sql query and call it from the script using Ajax.
jQuery code:
$.ajax({
type: "POST",
dataType: "json",
url: 'endpoint to php script',
success: function(data) {
$('.timer').countTo({
from: data.startFrom,
to: data.endOn,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
},
error: function(error) {
console.log(error);
}
});
PHP code:
<?php
//I assume you know how connect to your database and get data
header("Content-Type: application/json", true);
$result = array(
'startFrom' => 1000,
'endOn' => 9000
);
echo json_encode($result);
I thnik it's clear and explain this code is not needed

i want to get data from php file with ajax once per 5 min

I'm get data from excel file with php.After this data get from php file with ajax.In fact, I want to get data from excel file once per 5 min and print page.How can i do?
data.php
include "Classes/PHPExcel/IOFactory.php";
try {
$url="https://docs.google.com/spreadsheets/d/1ngOuUvGk07r69HEonmYdjl9En1F1COAB8fAhNXNT1Y8/pub";//Bu url 'i load'ın içine girdiğimde File not exist hatası veriyor.Ben localde denemek için aşağıdak inputfile .
$inputFile = 'a.xlsx';
$objPhpExcel = PHPExcel_IOFactory::load($inputFile);
$rows = $objPhpExcel->getActiveSheet()->toArray(null, true, true, true);
$i=0;
$data_en=array();
$data_tr=array();
$word=array();
foreach ($rows as $row)
{
$i++;
$data_en[$i] = $row['C'];
$data_tr[$i]= $row['D'];
echo $data_en[$i];echo "<br>";
}
}
catch(PHPExcel_Exception $e)
{
echo $e->getMessage();
}
index.html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("data.php", function(data){
$('#container').html(data);
});
});
</script>
<body>
<p id="container"></p>
</body>
You need to use setInterval() javascript function and set it to 5 minutes.
The JavaScript setInterval() function can be used to automate a task
using a regular time based trigger.
also you can clear scheduled work by clearInterval()
it is a native JavaScript function.
var duplicateWork = setInterval(function() {
// Do something every 1 seconds
}, 1000);
// To cancel scheduled work use similar code
clearInterval(duplicateWork);
look at the example :
var l = $('#list');
var duplicateWork = null;
var seconds = 1000 * 2;//2 second
$('#start').click(function(){
$('#title').html('Start : add item once per 2 second');
duplicateWork = setInterval(function() {
// Do something every 2 seconds
l.append('<li>duplicate work</li>');
}, seconds);
});
$('#stop').click(function(){
$('#title').html('Stop');
clearInterval(duplicateWork);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>
<h3 id="title"></h3>
<hr />
<ul id="list">
</ul>
In your case , you can use similar code
$(document).ready(function()
{
var seconds = 1000 * (60 * 5);//5 minute
var refreshId = setInterval( function() {
$.get("data.php", function(data){
$('#container').html(data);
});
}, seconds);
});

How to display a message before auto refresh div using jquery

I am trying to display a message before an auto refresh div. I have created this code for the auto refresh.
$(document).ready(function()
{
if setInterval(function() {
$("#pagere").load(location.href + " #pagere");}, 10000);
});
I also need to display a message like "page auto refresh in 3 sec...". How can I do that?
Try this :)
$(document).ready(function()
{
var alertTimeSec = 3000; //alert time in ms
var delayTimeSec = 10000; //time delay to refresh in ms
setTimeout(function () {
alert("3 Sec more")
}, (delayTimeSec-alertTimeSec));
setInterval(function() {
$("#pagere").load(location.href + " #pagere");}, delayTimeSec);
});
<script>
setInterval(function()
{
$("#pagere_container").load(location.href + " #pagere");
}, 3000);
</script>
<div id="pagere_container">
<div id="pagere">
page auto refresh in 3 sec...
</div>
</div>
setTimeout(function() {
$('#load_status').show();
}, 5000);
$("#pagere").load(location.href + " #pagere");}, 10000);
-this will give you 5 sec of timeout before refresh

Wrong if statement jquery

So I have a counter which counts down to 0 so when it hits 0 I want it to do a pdo update. The problem is that the if statement lets the update happen on each page refresh and does not wait for the count to hit 0.
I have looked at the code and can not see where I am going wrong.
<?php $timer = '20'; ?>
window.onload = function(){
(function(){
var counter = <?php echo $timer ; ?>;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
document.getElementById( "response" ).innerHTML = "<div style=\"float: right; display: inline-block; margin: 6px;\"><div class=\"skip_btn\">
<?php
$sqll = "UPDATE users SET coins=coins+? WHERE username=?";
$q = $db->prepare($sqll);
$q->execute(array('1',$_SESSION['username']));
$sqll2 = "UPDATE websites SET clicks_left=clicks_left-? WHERE id=?";
$q2 = $db->prepare($sqll2);
$q2->execute(array('1',$row['id']));
?>
</div></div><div style=\"clear:both;\"></div>";
}
}, 1000);
})();
}
I have just fixed it buy using a parser
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('parser.php');
}, 10000);
});
</script>
Thanks for the warm welcome tot he site tho.
Using jQuery try the following:
$(document).ready(function() {
var counter = 20;
setInterval(function() {
if( counter == 0 ) {
$.post("url/to/php");
}
else {
$("#div_for_showing_counter").html(counter);
counter--;
}
}, 1000);
});
This way you separate client side from server side. You can do whatever you want in the php file. If you need a callback or you need to pass data to the php file then simply modify the $.post to something like this:
$.post("url/to/php", { "key1": "value1", "key2": "value2" }, function(data) {
alert(data);
});

Call a function outside of a dynamic jquery slider

I am dynamically creating my sliders and in the "Slide" event and "Stop" event I would like to call a function that is defined in the non dynamic content. I can get the functions to work if I create them each time with the slider, but that seems like a lot of redundant code?
Non Dynamic function
$(document).ready(function() {
var converSecondsToMinutes;
convertSecondsToMinutes = function(secondsEntered){
var secondsEntered = secondsEntered;
var time = parseInt(secondsEntered,10);
time = time < 0 ? 0 : time;
var minutes = Math.floor(time / 60);
var seconds = time % 60;
minutes = minutes < 9 ? "0"+minutes : minutes;
seconds = seconds < 9 ? "0"+seconds : seconds;
var newTime = minutes+":"+seconds
console.log(newTime);
return newTime
}
});
Dynamic jQuery slider
<?php
query...
result...
for(...){
?>
<Script>
$( "#slider"+<?php echo $id; ?> ).slider({
animate: true ,
value: 0,
min: 0,
//dynamic grab this
max: <?php echo $playtime_seconds; ?>,
step: 0.01,
start: function( event, ui ) {
....
},
slide: function( event, ui ) {
audio = ....
audio.currentTime = ui.value;
progress_seconds = parseFloat(audio.currentTime.toFixed(2));
progress_seconds = $(function(){convertSecondsToMinutes(progress_seconds);});
$('#progress_seconds'+<?php echo $id; ?>).html(progress_seconds);
},
stop: function( event, ui ) {
....
}
}
});
});
}
I cut and paste the parts of the code that were important to the question.
This is the line that is not working: $('#progress_seconds'+).html(progress_seconds);
You edited just after I commented, so my comment no longer made sense, the $(function(){ part of your code is not necessary, try just using:
progress_seconds = converSecondsToMinutes(progress_seconds);
And spelling errors in code are a real issue with me, conver has a t at the end.
There is also no need to wrap your function in $(document).ready(), declare it like this:
function convertSecondsToMinutes(secondsEntered)
{
var time = ...
...
}

Categories