why is the alert box not displaying? - php

This is my code. It should display the alert box if the reset date stored in a textfile is equal to the current date and the data from the tables(mysql) are not zero.. Then it should reset the values to zero and delete other records. I've tried echoing the if statement and it's 1.Not sure why the alert box is not popping up..
<?php
function reset1(){
$sql=mysql_query("UPDATE tbl_txbookStock SET suppliedQuantity=0, boughtQuantity=0");
$sql=mysql_query("DELETE FROM tbl_order");
$sql=mysql_query("DELETE FROM tbl_order_book");
//overwrite date
$myFile = "config/config.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$resetDate = fread($fh, filesize($myFile));
fwrite($fh,date("m/d/Y",strtotime("+1 years")));
fclose($fh);
}
function getCurrentDate(){
return date('m/d/Y');
}
function resetDateIsToday($resetDate){
$itIs=false;
if($resetDate==getCurrentDate())
$itIs=true;
return $itIs;
}
function isReset(){
$isReset=false;
if(countZeroQuantities()==countBooks()){
$isReset=true;
}
return $isReset;
}
function countBooks(){
$sql=mysql_query("select count(bookID) as count from tbl_textbook");
$row=mysql_fetch_array($sql);
return $row['count'];
}
function countZeroQuantities(){
$sql=mysql_query("select count(bookID) as count FROM `tbl_txbookStock` where suppliedQuantity>0 OR boughtQuantity>0");
$row=mysql_fetch_array($sql);
return $row['count'];
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>TEXTBOOK ORDERING SYSTEM</title>
<link rel="stylesheet" href="templatemo_style.css">
<?php if (!isset($_SESSION['loggedin'])){ {?>
<?php if(resetDateIsToday(getResetDate())&&!isReset()){?>
<script type="text/javascript">
<!--
function confirmReset(){
var answer = confirm ("Reset is scheduled today.Do you really want to reset?")
if (answer===1){
<?php reset1();?>
window.location="index.php";
}else{
alert('Records not reset...');
window.location="index.php";
}}
// -->
</script>
<? }}}?>
</head>
<body>
</body>
</html>

I dont see where you execute confirmReset , maybe just write
window.onload =function(e){
confirmReset();
}
at the end of your script

confirm() returns true/false, and "true === 1" is not true.
just write your confirm control like this,
var answer = confirm ("Reset is scheduled today.Do you really want to reset?")
if (answer){
...
}

Related

PHP - Only the path is output instead of the page

I have a small problem with my function, which is supposed to do nothing but output the web page more dynamically via domain.com/index.php?page=start.
My problem is that only the path is displayed, but not the content of the start.html.
My index.php:
<?php
require_once './ext/config.php';
require_once './ext/functions.php';
$page = isset($_GET["page"]) ? $_GET["page"] : "default";
$pc = "$website_pages/$page" .".html";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $website_title; ?></title>
</head>
<body>
<?php echo $pc; ?>
</body>
</html>
My function.php:
<?php
function getPage($pagename) {
global $website_pages;
$path = "$website_pages/$pagename";
if (file_exists($path)) {
return openPage($path);
} else {
echo "Error";
return openPage("$website_pages/includes/default.html");
}
}
function openPage($pageurl) {
$fh = fopen($pageurl, "r");
$fc = fread($fh, filesize($pageurl));
fclose($fh);
return $fc;
}
?>
My config.php:
<?php
$website_title = "Title";
$website_charset = "UTF-8";
$website_pages = "includes";
?>
Output in browser:
includes/start.html
Maybe you can help me?
regards

Reset While loop value in PHP

I have a php loop, but it keeps printing the value next to each other instead of clearing the first loop value and replacing it with the new loop value. Here is my code.
while (1==1) {
$a=array("red","green","blue","yellow","brown");
$x=array_rand($a,3);
sleep(5);
print $a[$x[0]];
}
Basically it just needs to echo out a new random value on its own every 5 seconds, currently it doesn't remove the old value.
Try use jquery, the below example is for random numbers.
<script>
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*6);
//Do whatever you want with that number
$('#holder').html(rand);
}
</script>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Random Number</title>
</head>
<body>
<div id='holder'></div>
</body>
</html>
For random text
var names = ['test1', 'test2', 'test3', 'test4'];
setInterval(function() {
var rand = Math.floor(Math.random() * 4);
document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>
I am not sure if i understand what you are trying to accomplish, but I think this is what you are trying to do.
$a=array("red","green","blue","yellow","brown");
while (count($a)) {
$x=array_rand($a);
sleep(5);
echo chr(13). $a[$x];
}

Simple visit duration logger with AJAX

I have problem with logging visit duration.
I wrote test html file like this:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
alert("test");
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
var myAjax = new Ajax.Request('visitor_log/ajax_store_visit_duration.php?visit_duration=' + this.chrono.toString(),{
method: 'get',
onComplete:handlerFunction
});
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
PHP file (visitor_log/ajax_store_visit_duration.php):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
log($text);
}
else die("error");
function log($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
When I type in browser:
http://localhost/visitor_log/ajax_store_visit_duration.php?visit_duration=123
it creates text file as I want, but it seems that AJAX call in onbeforeunload event is not working.
Whats wrong with my code?
Edit:
I created test function to find problem with AJAX call.
function testajax(){
this.chrono = new Date().getMilliseconds() - this.chrono;
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + 123, false); // async = false
blockingRequest.send();
return null;
}
window.onload = testajax;
</script>
</body>
This is not working too.
Ok, so purposefully NOT using jQuery:
here's the PHP:
<?php
function loggit($text) {
$myFile = "/tmp/test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
if(isset($_GET["visit_duration"])) {
$text = $_GET["visit_duration"];
loggit($text);
}
else die("error");
?>
here's the HTML:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "http://localhost/_TempFiles/temp.php?visit_duration=" + this.chrono.toString(), false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
</body>
</html>
you want to use an async request (see the false sent to blockingrequest.open) - but beware this is a BLOCKING request (hence the name).
Also I changed the name of the php function from "log" to "loggit" log is the php natural logarithm function...

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

Retrieve data from mysql by php to create flot graph

Hi i am trying to retrieve data from mysql database to create flot graph
can anyone walk me through this procedure or give me an idea of what to do
thanks
You probably want something like this. I haven't used flot but I looked at the example here.
<?php
//create array of pairs of x and y values
$dataset1 = array();
while ($row = mysql_fetch_assoc()) { //or whatever
$dataset1[] = array( $row['xvalue'], $row['yvalue'] );
}
?>
<script type="text/javascript">
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
//plot
$(function () {
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
Adding upon the example from #Tom Haigh:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Examples</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "some_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
query = "SELECT x_axis_values, y_axis_values FROM some_table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_axis_value'],$row['y_axis_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1); ?>;
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
</body>
</html>
as #Tom Haigh say work well, but you need to add another code to work well, I was using the example, but I discover in the source code it add to the result quotes " so to avoid this just add the: intval to the array, example:
<?php
$query = "SELECT valx, valy FROM chart";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$d2[] = array (intval($row['valx']),intval($row['valy']));
}
?>
This depends largely on your environment and requirements. There's lots of free tools out there you can use. One example is Flot that lets you use jQuery to build graphs. There's link to documentation on the Google Code page.

Categories