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
Related
I have a jQuery function that loads a PHP file (which gets a JSON response from an application) every 100ms. What I am trying to do is have two different counters, one which will increment every time a request is sent and another counter which will increment as soon as it gets a JSON response. At the moment I have the following which is not working, they are both just counting the number of requests being sent:-
JQUERY
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
PHP
require_once('scripts/php/controllers/curl.controller.php');
$postcode = 'LE11 5';
$postcode = rawurlencode($postcode);
$uri = 'http://192.168.1.110:8290/?pc='.$postcode; // Home
$response = CurlController::request($uri);
So my question is basically, how can I count the number of successful responses I am getting from .$get command?
Need to print count to .request, you were using countSuccess in both the statements
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
//need to print here
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
You can use $.ajax's success parameter. The function passed to this parameter will only run if an ajax request is successful.
$.ajax({
url:"",
type: "get",
beforeSend: function(){ requestCounter++ },
success: function(){ successCounter++ }
});
What are you defijning as a success?
The .get 'success' is that the server responded which it hopefully always will do.
If you are definign success as somthign working in the PHP script then in the PHP then in the jquery success function check what was returned in 'data' to see if it was succesful.
I generally return a Json encoded array with an element called 'result' that is either set to ture or false by the PHP and the jquery can simple act on that record.
I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this.
Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b
and the GET request is repeated infinite. Within the get request, the response is:
{"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes.
I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script.
Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.
Jquery:
jQuery_1_11_0('#check').on('submit', function (e) {
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
function updates() {
$.getJSON("lib/getter.php", function (data) {
$("#progressbar").empty();
$.each(data.result, function () {
percentage = this['percentage'];
if (percentage = null) {
percentage = 100;
$("#progressbar").html(percentage);
}
});
});
}
});
process.php
$urlsarray = array('google.com', 'yahoo.com', 'bing.com');
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
doing some things
$counter++;
$percentage = ($counter/$total) * 100;
$db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;
getter.php
include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
EDIT 2 UPDATE
function updates() {
$.getJSON("lib/getter.html", function (data) {
$("#progressbar").empty();
$("#progressbar").html(data.percentage);
});
}
EDIT 3
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
//$("#progressbar").empty();
console.log(data);
$("#progressbar").html(data.percentage);
if(data.percentage >= 100){
clearInterval(myInterval);
}
});
}
EDIT 4. changed getter.php
include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
$percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
and the js script
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
var percentage = data.percentage;
$("#progressbar").html(percentage).show();
if(percentage >= 100 || typeof percentage !== 'undefined'){
clearInterval(myInterval);
}
});
}
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
var validatef = $("#url").val();
var validaterror = $('#errorvalidate');
if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
validaterror.text('Please enter domain names in the text area');
e.preventDefault();
} else {
validaterror.text('');
$.ajax({
type: 'post',
url: 'lib/process.php',
data: $('#check').serialize(),
success: function (data) {
$("#result").html(data); // apple
// $("#progressbar").knob().hide();
}
});
e.preventDefault();
} // ending the else
});
I cant help but wonder:
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.
Maybe replace the above with:
var myInterval = setInterval(function(){
updates();
}, 1000);
then, on the updates function
if(percentage >= 100){
clearInterval(myInterval);
}
By the way, doing:
if(percentage = null){
...
}
Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:
if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
...
}
Look at what you're sending back to your JS code from PHP:
echo json_encode(array('percentage' => $percentage));
Literally that'll be
{"percentage":42}
In your JS code, you then have:
$.getJSON("lib/getter.php", function (data) {
^^^^---the data coming back from PHP
....
$.each(data.result, function () {
^^^^^^---since when did you put a "result" key into your array?
For this JS code to work, you'd have to be doing
echo json_encode(array('result' => $percentage));
^^^^^^---note the new key.
And note that since you're sending back a SINGLE object in the JSON, with a single key:value pair, there is literally no point in using your inner $.each() loop. You could just as well have
$("#progressbar").html(data.percentage);
I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}
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 = ...
...
}
This is a sample dynamically updated chart:
http://www.highcharts.com/demo/dynamic-update
The chart is updated every second with the the date as the x value and a random number as the y value.
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
How would I rewrite load to fetch x and y from another webpage using AJAX, rather than generating the values within the function?
I take it what you want is the sample load method but with the lines that set x and y replaced with an AJAX call. You'll need to perform a fairly basic continuation-passing code transformation, turning the code after the point you want the asynchronous call into a function that's passed to the asynchronous call. "Continuation" simply means "the rest of the calculation, from a given point forward". In the code sample, that's the call to series.addPoint. The pattern for this is you transform:
function f(...) {
(1)
result = sync(...);
(2)
}
into:
function f(...) {
(1)
async(..., function (result) {
(2)
});
}
If (2) returned a value in the original function, then the call to f must also be rewritten using continuation passing style, adding an extra parameter to hold the continuation.
The other thing you should do is make sure the PHP script outputs the numeric pair as valid JSON, either as an array of two numbers (which can be passed directly to the series.addPoint call after parsing), or as an object with properties "x" and "y".
Note that, due to the nature of network communication, the data may not arrive in a timely manner, resulting in a graph with irregular intervals.
Here's the gist, wrapping up the nuts-and-bolts of the asynchronous call into a function named ajaj. The sample assumes the browser supports the necessary standards for XMLHttpRequest and the JSON parser.
/* Asynchronous Javascript And Json */
function ajaj(url, succeed, fail) {
if (! fail) {
fail = function() {};
}
var xhr = new XMLHttpRequest;
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState==4) {
if (200 <= xhr.status && xhr.status < 300) {
succeed(JSON.parse(xhr.responseText));
} else {
// error
fail(xhr.status, xhr.statusText, xhr.responseText);
}
}
};
xhr.send();
return xhr;
}
...
url: '...',
load: function() {
// ensure only one data load interval is running for this object
if (this.updateInterval) {
return;
}
// set up the updating of the chart each second
var series = this.series[0];
this.updateInterval = setInterval(function() {
ajaj(this.url,
function(point) { // success
series.addPoint(point, true, true);
},
function(status, statusText, response) { // failure
...
}
);
}, 1000);
}
JS libraries provide their own version of ajaj, often with more features. If you're doing anything of any complexity for a production site, look into adopting one. If you're using jQuery (as the tag suggests), you can, for example, use jQuery.get:
load: function() {
if (this.updateInterval) {
return;
}
// set up the updating of the chart each second
var series = this.series[0];
this.updateInterval = setInterval(function() {
jQuery.get(this.url,
function(point, textStatus, jqXHR) { // success
series.addPoint(point, true, true);
}, 'json'
);
}, 1000);
}
The server side of things is dead simple. time() returns a Unix timestamp, rand() returns a (not very) pseudorandom number (though good enough for a demo), and json_encode(), well, you can figure that out.
<?php
header('Content-type: application/json');
echo json_encode(
array(
time(),
rand() / getrandmax(),
));
I think you want a recursive call to setTimeout:
function update(series){
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
setTimeout(function() { update(series); }, 1000);
}
And then:
load: function() {
var series = this.series[0];
update(series);
}
Or better yet, try something like this:
function update(){
var series = yourChart.series[0];
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
setTimeout(update, 1000);
}
And then:
load: update
EDIT
If you're wanting to get a random number as an integer, something like this should do it (depending on the range of the number you want)
Math.floor(Math.random() * 10)
random will return a number in the range [0, 1), and floor will chop off any decimal points.
See random docs