Javascript/Jquery using mysql for initial config - php

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;

Related

Counter between 2 values with Daily Reset

I need help creating a counter that starts from 1 value (2000000) and ends at 2nd value (2500000), resets every day and does not restart upon page load.
I was able to get almost exactly what I want with javascript - but this restarts on page load/refresh. I imagine I need to write this in PHP, but I can't figure out how - any help/pointers would be awesome.
Here is the javascript example on JSfiddle and below:
var start = 200000001;
var end = 250000000;
var interval = 578;
var refreshIntervalId = setInterval(function(){
if(start <= end){
$("#start").text(start++);
}else{
stop();
}
},interval);
function stop(){
clearInterval(refreshIntervalId);
}
it's possible to solve you problem with ajax function and get the value from a database.
if you want use Cronjob and php for your probelm and dont work with database , use text file .
save your current number in a text file , i write a function for you a sample below :
function yourfunction($start,$end){
$perv = file_get_contents("num.txt");
if($perv <= $end){
$current = $perv++;
file_put_contents("num.txt","$current");
}
}

Javascript countdown not working for php loop

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.

Auto refreshing unlimited divs

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 />");
});

How to save a file to the server by pressing a button in Javascript

Ok so I'm experimenting with the in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.
I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.
When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here How to get JavaScript function data into a PHP variable attempts to pass this into a php file to save.
However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?
CODE:
Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:
<button type="button" onclick="saveDrawing()" id="saveButton">Save</button>
This calls the following in a separate JS file
function saveDrawing(){
// First check that not drawing and have data
if (!readyToDraw && clickX!=null){
// If ready then pass back to the PHP file the data
$url = 'file_save_test.php';
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
}
else {
alert("Please add some coordinate points and press Finish before saving");
}
}
and file_save_test.php contains only the following
<?php
// retrieve data from the JS
$buffer_data['x_coords'] = $_GET['x_coords'];
$buffer_data['y_coords'] = $_GET['y_coords'];
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
// first want to open a file
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'w');
// now to loop through arrays and write!
/*for ($i = 0; $i < sizeof($x_s); i++){
fwrite($file_handler, "$x_s[i], ");
fwrite($file_handler, "$y_s[i]\n");
} */
fclose($file_handler);
?>
In your PHP file it looks like your fwrite code is commented out. Are you expecting it to write to that data_test.txt file? Try changing your PHP file to print the results and have it echoed back to your javascript to see if the data is getting communicated properly.
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()},
function(data){
alert("Data Loaded: " + data);
});
PHP
print_r($_GET);
EDIT
Change your PHP file to something like this if it's alerting the data properly (it should append the coords to your file):
<?php
// retrieve data from the JS
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'a');
fwrite($file_handler, "$x_s, $y_s \n");
fclose($file_handler);
?>
EDIT 2
Update your for loop to your original code
for ($i = 0; $i < count($x_s); $i++){
fwrite($file_handler, $x_s[$i] . ", ". $y_s[$i] . "\n");
}
What I would do is have your save button call jQuery's $.post() method. Post the data to another PHP file that either inserts it into a database or saves it as a file. I don't recommend using the original document to post the data to because the client would have to download the entire DOM and the server would run any other code that you don't need.
That's as much as I can really help you without seeing any of your code.
I would send the data into a new php script called saveCoords.php or something..
You say you already have the coordinates in a JavaScript array, so it would look something like this...
//JAVASCRIPT FUNCTION which will request php file to store info
function storeCoords(xCoordArray, yCoordArray){
var xCoords = JSON.stringify(xCoordArray);
var yCoords = JSON.stringigy(yCoordArray);
var request = new XMLttpRequest(); //will need to change for older ie
request.onreadystatechange = function(){
//functions to handle returning information from php file..
}
request.open("GET","saveCoords.php?xCoords="+xCoords+"&yCoords="+yCoords, true);
request.send();
}
And then saveCoords.php file would look something like this:
<?php
$xCoords = json_decode($_GET['xCoords']);
$yCoords = json_decode($_GET['yCoords']);
//now you have a php array of xCoords and yCoords, which you can store
?>
Thats a skeleton but I think it hits on the major points, but comment with any questions.

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Categories