Give parameters to a function called by setInterval - php

I have the following function:
<script>
var count=900;
var countM;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
countM=Math.floor(count/60);
if (count <= 0)
{
clearInterval(counter);
return;
}
for(var i=0; i<10; i++)
{
document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs"; // watch for spelling
}
}
</script>
And I am displaying it like this:
<span id="<?php echo "timer".$theCounter; ?>"></span>
$theCounter++;
The problem its that I want to call it giving it a parameter, which will be count and I have no idea how to do it.

'I want to call it giving it a parameter, which will be "count"'
Something like the following:
function createTimer(count) {
var countM,
counter=setInterval(timer, 1000);
function timer()
{
count -= 1;
countM = Math.floor(count/60);
if (count <= 0) {
clearInterval(counter);
return;
}
for(var i=0; i<10; i++) {
document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs";
}
}
}
...will give you a function, createTimer(), that you can call with a parameter for the count:
createTimer(900);
If you're saying you want different spans to have different counters then you can do this:
function createTimer(count, elementID) {
// code exactly the same as above function except
// remove the `for` loop and just reference the elementID
// passed into the function:
document.getElementById(elementID).innerHTML=countM+"mins. "+(count%60)+ " secs";
}
createTimer(900, 'timer1');
createTimer(200, 'timer2');
// etc.
Demo: http://jsfiddle.net/dUTk3/1/

Like this?
var counter = window.setInterval(function() {
timer('parameter');
}, 1000);
I do not see what is the relationship between the javascript and PHP parts.

Use the bind function prototype to create a function with default parameters.
timer.bind(null,count-1);
The first argument is function context (null means global), optional following parameters is set tho function arguments from left. The result is new function. So in your code:
function timer(count) {
console.log(count); // do some stuff
if(count>0) setTimeout(timer.bind(null,count-1),1000);
}
timer(10); // counts from 10 to 0 in 1s interval
See the fiddle

Related

Want to reuse jQuery function making a function to use again and again

<script>
// Roti6p20tk
$(function () {
$("#distributedPacketForRoti6p20tk, #bonusForRoti6p20tk, " +
"#replaceForRoti6p20tk, #returnForRoti6p20tk").on("keydown keyup", sumForRoti6p20tk);
function sumForRoti6p20tk() {
$("#totalSalePacketForRoti6p20tk").val(Number($("#distributedPacketForRoti6p20tk").val())
- Number($("#bonusForRoti6p20tk").val()) -
Number($("#replaceForRoti6p20tk").val()) - Number($("#returnForRoti6p20tk").val())
);
$("#salesInAmountForRoti6p20tk").val(Number($("#totalSalePacketForRoti6p20tk").val()) * 20
);
}
});
// Roti4p14tk
$(function () {
$("#distributedPacketForRoti4p14tk, #bonusForRoti4p14tk, " +
"#replaceForRoti4p14tk, #returnForRoti4p14tk").on("keydown keyup", sumForRoti4p14tk);
function sumForRoti4p14tk() {
$("#totalSalePacketForRoti4p14tk").val(Number($("#distributedPacketForRoti4p14tk").val())
- Number($("#bonusForRoti4p14tk").val()) -
Number($("#replaceForRoti4p14tk").val())
- Number($("#returnForRoti4p14tk").val())
);
$("#salesInAmountForRoti4p14tk").val(Number($("#totalSalePacketForRoti4p14tk").val()) * 14
);
}
});
// final sum For Roti
$(function () {
$("#extSaleForRoti6p20tk, #extSalesForRoti4p14tk, " +
" #dueReceivedForRoti, #dueInAmountForRoti, " +
"#expAndComForRoti").on("keydown keyup", finalsumForRoti);
function finalsumForRoti() {
$("#totalSaleAmountForRoti").val(Number($("#extSaleForRoti6p20tk").val())
+ Number($("#extSalesForRoti4p14tk").val()) +
Number($("#salesInAmountForRoti6p20tk").val())
+ Number($("#salesInAmountForRoti4p14tk").val())
);
$("#totalReceivedForRoti").val(Number($("#totalSaleAmountForRoti").val())
+ Number($("#dueReceivedForRoti").val())
- Number($("#dueInAmountForRoti").val())
- Number($("#expAndComForRoti").val())
);
}
});
</script>
Here is the html code
This is my HTML code With Jquery function
I want to reuse these jquery function. I just want to send parameter then this function will do the same work for all.
These above function will do the same as i send parameter.
How to reuse jquery function without copy paste it again and again?
Can you show me the way or a tutorial?
I want to reuse the code. I need it more that five times. but i need to copy paste it and change the id or variable but i want to make a function which can do the same. i need to just send the parameter every time . :)
You can write a Javascript function that takes the list of IDs as an argument.
function sumForFields(totalid, salesid, inputids, salesmultiplier) {
$(inputids.join(',')).on("keydown keyup", function() {
var total = Number($(inputids[0]).val());
for (var i = 1; i < inputids.length; i++) {
total -= Number($(inputids[i]).val());
}
$(totalid).val(total);
$(salesid).val(total * salesmultiplier);
});
}
Then you can write:
sumForFields('#totalSalePacketForRoti6p20tk', '#salesInAmountForRoti6p20tk',
['#distributedPacketForRoti6p20tk', '#bonusForRoti6p20tk', '#replaceForRoti6p20tk', '#returnForRoti6p20tk'],
20);
This is for the first two functions. The last one has different structure, since it's mixing addition and subtraction when it combines the fields, not just subtracting everything like the first two.

store value in "add" button and "equal" button and post to php

I want to make a calculation and add button to store the First operand and the "+" then remove all the number so i can input the second operand. Than input the second operand. After that click button to send First operand , second operand and "+" to php.
It is the demo
i haven't finish the php code and it is just a "test" code to alert out the result.
My code is not working in some reason i don't know.
<?
php print_r($_POST);
?>
There are a few edits you need to make to your js code.
(1) in your $(document).on('click', 'button.number', function () { you need to check if the current value is a .function (operator), and if so add the operator to memory before setting the value to the number. I used $.inArray($show.val(),['+','-','x','/']) !== -1 which checks to see if it is in the array.
(2) changing your $("#add").click(function () { to $(document).on('click', 'button.function', function () { allows you to use all your .function (operator) buttons for this code, and not just the +.
(3) you need to add the current value to memory before you post memory to your php.
(4) you need to change execute: $.show.val() to execute: memory
$(function () {
var $show = $('#display');
var currentDisplay = "";
$show.val(0);
$(document).on('click', 'button.number', function () {
if ($show.val().length >= 8) {
$show.val("Error");
} else if ($show.val() == "Error") {
$show.val("0");
}
// (1) check if current value is a .function
else if ($.inArray($show.val(),['+','-','x','/']) !== -1) {
var addOp = $show.val();
if (addOp) memory.push(addOp);
$show.val($(this).val());
}
else {
$show.val(($show.val() == "0" ? "" : $show.val()) + $(this).val());
}
});
$("#clear").click(function () {
$show.val("0");
});
$("#ce").click(function () {
if ($show.val().length >= 2) {
$show.val($show.val().substring(0, $show.val().length - 1));
} else {
$("#ce").trigger("click");
}
});
var memory = [];
// (2) changed from $("#add").click(function () { so all functions are registered
$(document).on('click', 'button.function', function () {
var addnum = $show.val();
if (addnum) memory.push(addnum);
$show.val($(this).val());
});
$('#equ').click(function () {
// (3) add current value to memory
var addnum = $show.val();
memory.push(addnum);
// (4) change execute: $show.val() to execute: memory
$.post("calculation.php", {
execute: memory
}, function (data,status) {
$show.val(data);
var e = memory.join('');
memory = [];
});
});
});
Then in calculation.php you want to loop through the array and add/subtract depending on the operator.
<?php
if(isset($_POST['execute']) && is_array($_POST['execute'])) {
$total = (int)$_POST['execute'][0];
for($i=1;$i<count($_POST['execute']);$i+=2){
switch($_POST['execute'][$i]){
case '+': $total += (int)$_POST['execute'][$i+1];break;
case '-': $total -= (int)$_POST['execute'][$i+1];break;
default : $total += (int)$_POST['execute'][$i+1];
}
}
echo $total;
}
else echo 'Error';
?>
(note: I only did + and - in php, assuming that you could figure out how to add the * and /)
here is an updated jsFiddle - http://jsfiddle.net/9t78jd47/3/ (it uses js code, instead of $.post() to mimic sending memory to calculation.php

Javascript compare string in an array

function getPublicLink() {
var div = document.getElementById('links'); // anchor tag
var url;
for(var x in div){
url += div[x].href;
}
}
This is for getting the list. My Problem is that I want to compare it with the json results below. If there is a matched. I will alter the anchor tag to remove the href attribute or make the text Connected ( Now it is "Invited"). The Linkedin connection code is:
function displayConnections(connections) {
var members = connections.values;
var publicUrl;
for(var member in members) {
publicUrl += members[member].publicProfileUrl;
}
}
My problem is they are in a big string. What i want is to compare them one by one. I'm out of ideas since I'm just a JS beginner. Thanks for your input!
I've found the answer.
for(var i in publicUrl) {
for(var j in url) {
if(url[j] === publicUrl[i]) {
alert("Found " + url[j]);
}
}
}

Get data through xhr from PHP

I'm trying to get some data from a PHP file which only gives a number after executing:
<?php
include '../assets/class/login/loginsys.php';
$extension = new extension;
$count = $extension->userCount();
echo $count;
?>
So the $count variable will be just a number. And I'm trying to retrieve that number and put it in a js variable for further use ( I need it a few times, if it were only once I would have used $.get() and applied it to the container I need ):
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send();
I have tried the method above with little success, but I also tried it like this:
var users = $.get('admin/user-count.php', function(data) {
console.log('There are '+data+' users found');
return data;
});
The same result, nothing. So what am I doing wrong or how should I do it right ?
EDIT I have made a little mistake that I fixed now, the first method works as well as the second one. but now I need to store the data I get with the first method into a variable so I can use it later on. How do I do that and also which of the two methods is better ?
I would use the second code if you already have jQuery included:
$.get('admin/user-count.php', function(data)
{
// Don't use "var" here, otherwise the variable won't be global!
myGlobalVar = parseInt(data, 10);
// Also possible: window["myGlobalVar"] = parseInt(data, 10);
});
If you want to use pure JavaScript:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onload = function(evt)
{
myGlobalVar = parseInt(oXHR.responseText,10);
}
oXHR.onerror = function(evt)
{
alert("Error!");
}
oXHR.send();

How to load more on PHP array?

I use jQuery (I found this code in an answer, tested and working) to show people.php and reload it every 100 seconds. People.php has an array peoples where there are saved name, job, birthday.
As you can see, the output stops at 30 names. How can I have a twitter like button "load more" and show 10 more at a time? Additionally, when there are e.g. 50 more people's name (assuming that the user clicked "load more" twice, will the jQuery timeout reload, returned them at 30 as the beginning ?
<script>
var timerID;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php', function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
How about passing a parameter to the URL in your load(..) call?
$(function () {
var startAt = 0;
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?start_at=' + startAt, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
startAt += 30;
});
}
});
Then in people.php you could get the passed parameter using $_GET:
$start_at = 0;
if (isset($_GET['start_at']) && is_numeric($_GET['start_at'])) {
$start_at = (int) $_GET['start_at'];
}
for ($i = $start_at; $i < min($start_at + 30, sizeof($peoples)); $i++) {
echo $peoples[$i]->name;
}
Well what you could do is save a variable that contains the number of people, this example should give you a good view of what i mean.
<script>
var timerID;
var cap;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?cap='+cap, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
<?php
foreach ($peoples as $people) {
if(++$i > $_GET['cap']) break;
echo $people->name;
}
?>
So all you have to do, is change the cap variable, you could do this easily making a javascript function and call this via a onClick event.

Categories