Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.
Related
I want to create a counter. I have a foreach loop value. I want show the count while the script is running. How can set a counter while the script is running?
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
echo "<p class='test'>Total Matched : </p>";
echo "<br>";
echo "Not Found : " .$k;
This question is (or at least should be) entirely unrelated to PHP. Use PHP to output your data, including the total count. Then, use javascript/jQuery to create a visual effect of counting from 0 to the total number, for example on document ready.
<p class='test'>Total Matched : <span>888</span></p>
Javascript
$(function(){
var item = $('.test > span');
var total = parseInt(num.text());
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
`
This won't work. The output is only shown after the PHP has finished executing.
PHP stands for: "PHP: Hypertext Preprocessor", notice the "Preprocessor" part, it preprocesses the page and creates the HTML, it cannot modify the HTML once it's ran.
You Can't show php's foreach's count while the script is running.
PHP doesn't work that way. PHP is a preprocessor for HTML. It converts the dynamic code into plain html at server side as a whole, and then it sends the whole HTML file to browser.
Thus, you don't have option to show php loop's counter value to the user side.
You Can alternatively use Ajax. But again, PHP will send whole ajax response at once only after php script finishes execution. You have to implement some javascript loop mechanism at client side to show the counter value one by one as suncat100 suggested.
If you want to show value updating animation to user you can try this,
PHP
$i=0;
foreach ($_productCollection as $_product){
$attrapivalue = $_product->getAttributeText('apivalue');
$prosku = $_product->getSku();
if (!in_array($prosku, $array) && $attrapivalue=="No"){
echo "<p class='count'>";
$i++;
echo "</p>";
}
}
HTML (JS)
<script>
$(function(){
var item = $('.test > span');
var total = <?php echo $i?>;
var counter = 0;
var timer = setInterval(function(){
counter ++;
item.text(counter);
if(counter >= total) clearInterval(timer);
}, 10);
});
</script>
</body>
Use the both php and JS code in same page. put the JS code part just before ending </body>.
So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?
change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.
So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
I am currently able to refresh a div on my website using jquery with php. This works well to a point. The issue is that the data being refreshed currently is an entire table. The code being used in the header is as follows:
<!-- DIV REFRESH START -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#datatable').fadeOut('slow').load('data/table.php').fadeIn("slow");
}, 10000);
</script>
<!-- DIV REFRESH END -->
As you can see, it is refreshing a specific div with a specific page. I'm very novice with jquery and java based coding in general as I'm sure will be evident in this question.
Is it possible to do the following:
The table is actually created in a php function due to the the fact that the number of rows changes all the time. Is it possible to have it refresh the function specifically rather than a page that is just calling the function?
The table currently refreshes completely. This is just to update one figure on each row. It would be much cleaner to have it only refresh each figure on the row but due to the flexible nature of the table and the fact that it is part of a function would this be possible? If so, how would it be possible? I know I could have each div on each row to have a unique div name which I could then take into account in the script section at the top of the page but would that not require having every possible div name added with the same code repeated?
Though I know it is possible to have the item refresh based on when something in the database changes rather than by a time delay but what would be the best way given the requirements listed above?
I could be way off and it's a simple answer to each question but I appreciate any and all input.
Thanks!
p.s. if it helps, the function I'm currently using to create the table is the following (I know it can be made to function much cleaner but it is a bit of a learning project):
function portalTable($venueId, $eventId)
{
echo "<table class='basic-table'><tr class='th'><th>Portal Name</th><th>Scanned</th></tr>";
$grandTotals = array();
$portalSql = mysql_query("SELECT * FROM portal WHERE id_venue = $venueId");
while ($portalRow = mysql_fetch_array($portalSql))
{
$portalId = $portalRow['id_portal'];
$portalName = $portalRow['name_portal'];
if($portalId&1) {$gray = "dg";} else {$gray = "lg";}
$sql = mysql_query("SELECT * FROM scan WHERE id_event = $eventId AND id_portal = $portalId");
while ($row = mysql_fetch_array($sql))
{
$scanTotal = $row['total_scan'];
echo "<tr class='$gray'><td>$portalName</td><td>$scanTotal</td></tr>";
$grandTotals[] = $scanTotal;
}
}
$totals = array_sum($grandTotals);
echo "<tr class='basic-table-total'><td>Total</td><td>$totals</td></tr>";
// total failed scans
$sql = mysql_query("SELECT total_errors FROM errors WHERE id_event = $eventId");
while ($row = mysql_fetch_array($sql))
{
$totalErrors = $row['total_errors'];
echo "<tr class='basic-table-total'><th>Total Rejected Scans</th><th>$totalErrors</th></tr>";
}
echo "</table>";
}
$('div.myDiv').each(function(i, obj) {
$(obj).load('myURL.php');
});
That what you're looking for?
As for the large amount of data being sent? Don't send raw HTML!
Instead, use parseJSON in jQuery and json_encode in your PHP script to send a (much) smaller amount of data to the user, which can then be used by the client to make the table.
Handling the decoded JSON data is relatively simple in JavaScript. Once it has been decoded, it is now an accessible object. You can use an iterator (jQuery does this well).
$.each(myJSON, function(i, val) {
$('body').append(val + "<br />");
});
I'm using codeigniter and I have a timeout function using jquery. I just need to find a way to get a number (an int) from a field in the database the application is using and set the initial int in the javascript file to it. As you can see in the code '900000' needs to be dynamically received from a database table. Since it does not need ajax(does not need dynamically receive data in real time) I would like to find a lighter solution if possible. What would be the best practice in this situation?
$(document).ready(function () {
idleTimer = null;
logoutTimer = null;
idleWait = 900000; //15 minutes
logoutWait = 30000; //30 sec
timeUp = false;
Just use echo to output the value at that point in the script.
idleWait = <? echo $timeoutValueRetrievedFromDataBase ?>;
PHP will not run in your standard JS file without quite a bit of modification. First off, find the .php file where your <head> section is located. Find the first <script> tag, you will want to work before this. That way you can go ahead and set a variable that will be ready when your JS file gets loaded.
Right above your first <script> tag insert something like this
<script>
<?php
//you will need to connect to db here and get your timeout value from the database
//we assume $timeout has the correct value in it
echo "var phpTimeout = $timeout;"
?>
</script>
You would then go into the script you pasted into the question and do this
$(document).ready(function () {
idleTimer = null;
logoutTimer = null;
idleWait = phpTimeout; //this is the variable we set earlier in the <head> of the document
logoutWait = 30000; //30 sec
timeUp = false;