multiple records using the same script - javascript

I have built a voucher website, where each voucher has a countdown timer. When you view a voucher the countdown works fine, however...
I also have a summary page with multiple vouchers (using a repeat region on the recordset)... when I apply the script to each of the vouchers the script doesn't work.
The HMTL:
<h3 class="remaining"><?php echo $row_rs_dealItem['dateend']; ?> remaining</h3>
The JAVASCRIPT external file:
$(document).ready(function(){
$('.remaining').each(function(){
var expiry_date = Date.createFromMysql($(this).html());
var current_date = new Date();
console.log(expiry_date.getTime() );
console.log(current_date.getTime());
if (expiry_date.getTime() > current_date.getTime()) {
var time_diff = Math.floor((expiry_date.getTime() - current_date.getTime()) / (1000*60*60));
console.log(expiry_date.getTime() - current_date.getTime());
console.log(time_diff);
days_diff = Math.floor(time_diff / 24);
hours_diff = time_diff % 24;
$(this).html(days_diff + ' days ' + hours_diff + ' hours');
}
else{
$(this).html('expired');
}
});
});
Date.createFromMysql = function(mysql_string)
{
if(typeof mysql_string === 'string')
{
var t = mysql_string.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return null;
}
The JAVASCRIPT inline:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/script.js"></script>
<script type="text/javascript">
var reference = '<?php echo $row_rs_dealItem['reference']; ?>';
var today = Date.createFromMysql('<?php echo date('Y-m-d h:i:s'); ?>');
var contractstarts = <?php echo ($row_rs_dealItem['datestart'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['datestart'] . '")'; ?>;
var contractexpires = <?php echo ($row_rs_dealItem['dateend'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['dateend'] . '")'; ?>;
</script>
I hope this is enough data for you.
thanks

I realised that I had effectively copied the code from one page to another and the record sets had different names :(

Related

Accessing an Array outside of a While loop

I have a while loop which contains an array which is referencing another file: legProductionAllRecords.php. This file returns an array Which is then used in the loop. I want to be able to use the $orderArray in my javascript tableObj as shown however it is not working. And shows no results when I have no results in $inProgressArray. I also need to be able to use $inProgressArray outside of this loop.
index.php
$madeAt = 2;
$inProgressQuery ="SELECT * FROM leg_prod_inprogress WHERE madeat=".$madeAt;
$inProgressResult = mysql_query($inProgressQuery);
$orderArray = array();
$inProgressArray = array();
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)) {
$inPogressOrder = "-1";
if ($inProgressArray != false) {
$inPogressOrderNo = $inProgressArray['purchase_no'];
} else {
$inPogressOrderNo = -1;
}
require_once('legProductionAllRecords.php');
$allArray = legProductionAllRecords($madeAt, $inPogressOrderNo);
$orderArray = $allArray['allOrder'];
$inPogressOrder = $allArray['inprocessOrder'];
$toadyFinishedOrder = $allArray['todayFinishedOrder'];
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var tableObj = {
data: <?php echo json_encode($orderArray); ?>,
processingData:<?php
if(!empty($inPogressOrder)&&$inPogressOrder!=''){
echo json_encode($inPogressOrder);
}
else{echo -1;} ?>,
}
</script>
</head>
</html>
legProductionAllRecords.php
<?php
function legProductionAllRecords($madeAt,$inPogressOrderNo){
$dayquery = "SELECT * FROM manufacturedat WHERE ManufacturedAtID=".$madeAt;//$madeAt is either 2 or 1
$dayresult = mysql_query($dayquery);
$dayArray = mysql_fetch_array($dayresult,MYSQL_ASSOC);
$day = $dayArray['LegCompletionNoItems'].' days';
$qry = "SELECT a.PURCHASE_No, a.legstyle, a.legfinish, a.LegQty, a.legheight, ".
"a.addlegstyle, a.addlegfinish, a.AddLegQty, a.ORDER_NUMBER, a.specialinstructionslegs, ".
"b.surname, b.first ".
"FROM purchase AS a LEFT JOIN contact AS b ON a.contact_no=b.CONTACT_NO ".
"WHERE a.legrequired='y' ".
"AND a.completedorders = 'n' ".
"AND a.quote = 'n' ".
"AND a.orderonhold = 'n' ".
"AND a.contact_no <> 326314 ".
"AND a.contact_no <> 324273 ".
"AND a.contact_no <> 313820 ".
"AND a.ORDER_DATE >= '2015-12-31' ".
"AND (a.cancelled IS NULL OR a.cancelled <> 'y') ";
$result = mysql_query($qry);
$orderArray = array();
$returnArray['inprocessOrder'] = null;
$returnArray['todayFinishedOrder'] = null;
while ($temp = mysql_fetch_array($result,MYSQL_ASSOC)){
if(!empty($temp)){
$temp['surname'] = mb_convert_encoding($temp['surname'],"UTF-8");
//$temp['title'] = mb_convert_encoding($temp['title'],"UTF-8");
$temp['first'] = mb_convert_encoding($temp['first'],"UTF-8");
$qcQuery = "SELECT * FROM qc_history WHERE ComponentID=7 AND Purchase_No=".$temp['PURCHASE_No']." ORDER BY QC_Date DESC";
$qcresult = mysql_query($qcQuery);
$temp2 = mysql_fetch_array($qcresult,MYSQL_ASSOC);
if($temp2['QC_StatusID']== 20 && $temp2['MadeAt']==$madeAt ){//$temp2['QC_StatusID']== 20 &&
//=====================Change the date format to week:day===============================//
$temp2['formatedBCWExpected'] = date('d/m/Y',strtotime($day,strtotime($temp2['BCWExpected'])));
$tep_time = date_sub(date_create($temp2['BCWExpected']),date_interval_create_from_date_string($day));
$time = explode(':',date_format($tep_time,'W:w'));
$week = (int)$time[0];
$weekday = (int)$time[1];
if($weekday == 0){
$weekday = 5;
}
if($weekday == 6){
$weekday = 5;
}
$temp2['WDdate'] = $week.':'.$weekday;
//=======================End of Change the date format to week:day===============================//
$temp['qc_history'] = $temp2;
$temp['cname'] = $temp['first'].' '.$temp['surname'];
if($temp['PURCHASE_No'] == $inPogressOrderNo){
$returnArray['inprocessOrder'] = $temp;
}
else{
array_push($orderArray, $temp);
}
}
}
}
$returnArray['allOrder'] = $orderArray;
return $returnArray;
}
?>
I have tried the following:
I have used this answer to understand how to reference and update an array outside of a while loop
I have tried including a check for whether $inProgressArray is empty in the while loop like this.
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)||empty($inProgressArray))
however, there is an item in leg_prod_inprogress and it's not shown in the $inProgressArray outside the loop.
Editted 16/11/17 16:13 GMT: Added the details of legProductionAllRecords.php
Editted 2 17/11/17 08:43 GMT: Added the return statement of the return array of the function

strange error in javascript countdown

I'm building a webpage that shows multiple consecutive countdowns, depending from a text file.
Almost everything works now, only one thing still doesn't want to work.
The problem is this: when the timer hit's 00:00:00, it should switch to the next countdown, and start counting down, but what is does is showing some kind of glitch, it flashes between nan:nan:nan and 23:59:xx, like the countdown started again, counting down to the next day. I wrote some stuff to the console, and here I see that my function to set a new deadline in javascript is called, and the deadlinecounter does go up; but it goes up from 0 to 6 first, en later from 0 to 7. very strange I would say. Hope someone can help me!
this is my code:
<!DOCTYPE html>
<!-- php functions -->
<?php
$deadlineH = null;
$deadlineM = null;
$deadlineS = null;
$deadlineTitle = null;
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$fullArray = setFullArray($content);
$length = count($fullArray);
for ($i = 0; $i < $length - 1; $i++) {
$value = $fullArray[$i];
echo "var " . ($i + 1) . ": " . $fullArray[$i] ." <br>";
if((($i+1) % 4) == 0){
echo " ";
}
}
$hoursArray = [];
$minutesArray = [];
$secondsArray = [];
$titlesArray = [];
setArrays($fullArray);
function setArrays($fullArray){
$length = count($fullArray);
for ($i=0; $i < $length - 1; $i = $i+4) {
array_push($GLOBALS['hoursArray'], $fullArray[$i]);
}
for ($j=1; $j < $length - 1; $j = $j+4) {
array_push($GLOBALS['minutesArray'], $fullArray[$j]);
}
for ($k=2; $k < $length - 1; $k = $k+4) {
array_push($GLOBALS['secondsArray'], $fullArray[$k]);
}
for ($l=3; $l < $length - 1; $l = $l+4) {
array_push($GLOBALS['titlesArray'], $fullArray[$l]);
}
}
$numberoflines = getNumberOflines($fullArray);
echo "number of lines: " . $numberoflines . "<br>";
showDeadlines($fullArray);
function setFullArray($content){
$fullArray = preg_split("/(:|\n)/" ,$content); // splits the whole data txt file into small chunks, everything apart
return $fullArray;
}
function getNumberOflines($fullArray){
$numberoflines = (sizeof($fullArray) - 1) / 4;
return $numberoflines;
}
function showDeadlines($fullArray){ // won't be used in final thing
$length = count($fullArray);
for ($i=0; $i < $length-1; $i = $i + 4) {
$deadlineNumber = ($i + 4)/4;
$deadlineH = $fullArray[$i];
$deadlineM = $fullArray[$i+1];
$deadlineS = $fullArray[$i+2];
$deadlineTitle = $fullArray[$i+3];
echo "deadline " . $deadlineNumber . ": " . $deadlineH . ":" . $deadlineM . ":" . $deadlineS . " titel : " . $deadlineTitle . "<br>";
}
}
function setDeadline($fullArray){
$length = count($fullArray);
for ($i=0; $i < $length-1; $i = $i + 4) {
$deadlineNumber = ($i + 4)/4;
$GLOBALS['deadlineH'] = $fullArray[$i];
$GLOBALS['deadlineM'] = $fullArray[$i+1];
$GLOBALS['deadlineS'] = $fullArray[$i+2];
$GLOBALS['deadlineTitle'] = $fullArray[$i+3];
}
}
?>
<!-- end php functions -->
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="startTime()">
<div id="visible">
<div id="clock"><span> </span> </div><br>
<div id="countdown"> </div>
<div id="countdown"> </div>
<div id="title"> </div>
</div>
<p>
<?php
echo json_encode($hoursArray);
echo json_encode($minutesArray);
echo json_encode($secondsArray);
echo json_encode($titlesArray);
?>
</p>
</div>
<!-- javascript scripts -->
<script>
var hoursArray = [];
var minutesArray = [];
var secondsArray = [];
var titlesArray = [];
var deadlineCounter;
function startTime() {
var now = new Date();
// year, month, day, hours, minutes, seconds, milliseconds
var deadline = new Date(2016, 11, 20, 00 ,00 ,00 ,00);
deadlineCounter = 0;
var clockH = now.getHours();
var clockM = now.getMinutes();
var clockS = now.getSeconds();
setArrays();
setInitialDeadline(deadline);
startClock('clock');
startCountdown('countdown', deadline);
var t = setTimeout(startTime, 500);
}
function setArrays(){
hoursArray= <?php echo json_encode($hoursArray); ?>;
console.log( hoursArray );
minutesArray= <?php echo json_encode($minutesArray); ?>;
console.log( minutesArray );
secondsArray= <?php echo json_encode($secondsArray); ?>;
console.log( secondsArray );
titlesArray= <?php echo json_encode($titlesArray); ?>;
console.log( titlesArray );
}
function setInitialDeadline(deadline) {
deadline.setHours(hoursArray[0]);
deadline.setMinutes(minutesArray[0]);
deadline.setSeconds(secondsArray[0]);
document.getElementById("title").innerHTML = titlesArray[0];
}
function setNewDeadline(deadline){
console.log('new deadline set');
deadline.setHours(hoursArray[deadlineCounter]);
deadline.setMinutes(minutesArray[deadlineCounter]);
deadline.setSeconds(secondsArray[deadlineCounter]);
document.getElementById("title").innerHTML = titlesArray[deadlineCounter];
}
function getCountdown(deadline){
var countdownTotal = Date.parse(deadline) - Date.parse(new Date());
var countdownS = Math.floor( (countdownTotal/1000) % 60 );
var countdownM = Math.floor( (countdownTotal/1000/60) % 60 );
var countdownH = Math.floor( (countdownTotal/(1000*60*60)) % 24 );
return{
'countdownTotal': countdownTotal,
'countdownH': countdownH,
'countdownM': countdownM,
'countdownS': countdownS
}
}
function startClock(id){
var clock = document.getElementById(id);
var timeInterval = setInterval(function(){
var now = new Date();
var nowH = now.getHours();
var nowM = now.getMinutes();
var nowS = now.getSeconds();
nowH = checkTime(nowH);
nowM = checkTime(nowM);
nowS = checkTime(nowS);
clock.innerHTML = nowH + ':' + nowM + ':' + nowS;
}, 1000);
}
function startCountdown(id, deadline){
var countdown = document.getElementById(id);
var timeInterval = setInterval(function(){
var t = getCountdown(deadline);
//console.log(t);
//console.log(deadlineCounter);
countdown.innerHTML = checkTime(t.countdownH) + ':' + checkTime(t.countdownM) + ':' + checkTime(t.countdownS);
if(t.countdownH == 0 && t.countdownM == 0 && t.countdownS == 0){
deadlineCounter++;
setNewDeadline(deadline);
t = getCountdown(deadline);
}
}, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<!-- //end javascript -->
</body>
</html>
Thanks!
Correct calling the function startTime() inside itself like this: var t = setTimeout(startTime, 500);. Maybe it's better to remove this line from func body and write:
<body onload="setTimeout(startTime(), 500)">

Uncaught TypeError: Cannot read property 'textContent' of undefined

when i click the date value i having this "error
Uncaught TypeError: Cannot read property 'textContent' of undefined "
this is my code can you help me in determining the source of the error and how can i correct this
<?php
while($row = mysqli_fetch_array($query)){
$date = $row['Date'];
$time = $row['Time'];
$latitude= $row['Latitude'];
$longitude= $row['Longitude'];
$depth =$row['Depth'];
$magnitude = $row['Magnitude'];
//$array_lat_lon[] = $lat = $row['LAT'];
//$array_lat_lon[] = $lon = $row['LON'];
$the_arraypei[] = array($row['Date'] ); //added
//$the_array[] = array($row['LAT']."" , "".$row['LON']) ;
//$timestamp = strtotime()
echo '<tr class="normalRow"><td id="date2">'.$date.'</td><td border="1">'.$time.'</td><td border="1">'.$latitude.'</td><td border="1">'.$longitude.'</td><td border="1">'.$depth.'</td><td border="1">'.$magnitude.'</td></tr>';
}?>
<script>
function functiontoget($date) {
var x = document.getElementsByTagName("#date")[0].textContent;
document.getElementById("demo").innerHTML = x;}
</script>
<p id="demo"></p>
if you want to query elements by tag name you can use getElementsByTagName , but do you have a tag named #date ? #date is one element's id you need to use getElementById .
chage your javascript code :
function functiontoget($date) {
var x = document.getElementById("date").textContent;
document.getElementById("demo").innerHTML = x;
}
This is my code.
The problem is that when I click the first value($date) in the table the alert is presented but when I click the other value($date) no alert is presented.
It is like the only clickable one is the first value($date)
<?php
while($row = mysqli_fetch_array($query)){
$date = $row['Date'];
$time = $row['Time'];
$latitude= $row['Latitude'];
$longitude= $row['Longitude'];
$depth =$row['Depth'];
$magnitude = $row['Magnitude'];
echo '<tr class="normalRow"><td id="date2">'.$date.'</td><td border="1">'.$time.'</td><td border="1">'.$latitude.'</td><td border="1">'.$longitude.'</td><td border="1">'.$depth.'</td><td border="1">'.$magnitude.'</td></tr>';
}}
}
?>
<script>
$(document).ready(function() {
$("#date2").click(function() {
var x = $(this).text();
alert(x);
x = $(this).next().html();
alert(x);
...
});
});
</script>

Alert box is not showing in codeigniter models

in the model alert is not working. if condition is working,the only problem with the alert box, its not showing the dialog box.Please help..
public function setJumlahPenumpang ($idJadwal,$idPemesanan,$jml,$booked,$selected){
$data1 = $this->db->query('select p.jumlah_kursi, j.jumlah_penumpang, p.harga from tb_po p JOIN tb_jadwal j ON j.id_po = p.id_bus WHERE j.id_jadwal ='. $idJadwal);
foreach ($data1->result_array() as $dataa1) {
$tersedia = $dataa1['jumlah_kursi'] - $dataa1['jumlah_penumpang'];
if($tersedia < $jml){
?>
<script type="text/javascript">
document.location = '<?php echo base_url(); ?>proses/cekKode1/<?php echo $idPemesanan ?>';
alert("Tidak ada Bus Beroperasi");
</script>
<?php
}else{
$data3 = $dataa1['harga'] * $jml;
$this->db->query('update tb_pemesanan set harga = '.$data3.' where id_pemesanan = '.$idPemesanan);
$data = $this->db->query('select jumlah_penumpang from tb_jadwal where id_jadwal ='. $idJadwal);
$this->db->query("update tb_jadwal set booked = '".$booked."' where id_jadwal = ".$idJadwal);
$this->db->query("update tb_pemesanan set kursi = '".$selected."' where id_pemesanan = ".$idPemesanan);
foreach ($data->result_array() as $dataa) {
$data2 = $dataa['jumlah_penumpang'] + $jml;
$this->db->query('update tb_jadwal set jumlah_penumpang = '.$data2.' where id_jadwal = '.$idJadwal);
}
}
}
}
Try Echo Before Script Tag I hope So it 'll work....
if($package_id == NULL) {
echo '<script type="text/javascript">
window.location.href = "'.base_url().'"
</script>';
return;
die();
}

How to get the current record in the database

I have a database with the following record:
timer_id = 1
time = 498
I'm retrieving the record in the time column but it won't retrieve the current record. I have this code for retrieving it:
<script>
function start(){
div = "<?php $select = mysql_query('SELECT COUNT(*) AS num FROM tbl_timer',$connection); while($row = mysql_fetch_array($select)){ $num = $row['num']; } ?>";
var num = "<?php echo $num; ?>";
alert(num);
if(num == 0)
{
document.getElementById("form1").innerHTML = '<input id="time1" onChange="alert(\'Hallo\')" value="720"/>';
}
if(num !== '0')
{
var div = "<?php $select = mysql_query('SELECT COUNT(*) AS nu FROM tbl_timer',$connection); while($row = mysql_fetch_array($select)){ $nu = $row['nu']; } if($nu !== '0'){$select = mysql_query('SELECT * FROM tbl_timer',$connection); while($row = mysql_fetch_array($select)){ $time = $row['time']; $tc = $row['utc']; }}else{$time = 0; $tc= 0;} ?>";
var time = "<?php echo $time; ?>";
alert(time);
document.getElementById("form1").innerHTML = '<input id="time" value="'+time+'"/>';
document.getElementById("h").innerHTML = ' <button id="pt" onclick="pause()">Pause</button>';
secondPassed();
}
}
</script>
Whenever I alert the 'time' the output will be the previous record that was 510.
What will I do to get the current record every time it will be stored in the database.
There is no such thing as a 'current record', at least not in the way you are using it. Once you start your second query, the database starts all over at the beginning of the table. Also, there's no guarantuee that the order in which the rows are returned are the same.
I'm not sure what you are trying to do, but I suggest you read some tutorials on using WHERE clauses, ORDER BY, etc.

Categories