undefined from arrValue.start_date - javascript

I am trying to get from my database the start_date and end_date, however, I am getting "undefined" in console from arrValue.start_date or arrValue.(x) regardless of input.
unavailabletimes = [];
is_conflict = false
$.ajax({
url: '<%= preload_parking_path(#parking) %>',
dataTyp: 'json',
success: function(data) {
$.each(data, function(arrID, arrValue){
unavailabletimes.push([moment(moment.utc(arrValue.start_date).format('YYYY-MM-DD HH:mm')), moment(moment.utc(arrValue.end_date).format('YYYY-MM-DD HH:mm'))] );
console.log(arrValue.start_date);
})
var prestart_date = $('#reservation_start_date').datetimepicker('viewDate');
var start_date = moment(moment(prestart_date).format('YYYY-MM-DD HH:mm'));
var preend_date = $('#reservation_end_date').datetimepicker('viewDate');
var end_date = moment(moment(preend_date).format('YYYY-MM-DD HH:mm'));
if(end_date.diff(start_date, 'minutes') < 60){
var duration = 60;
}else{
if((end_date.diff(start_date, 'minutes') % 60) == 0){
var duration = end_date.diff(start_date, 'minutes');
}else{
var duration = ((end_date.diff(start_date, 'minutes') - (end_date.diff(start_date, 'minutes') % 60)) + 60);
}
}
unavailabletimes.forEach((unavailabletime)=> {
// unavailabletime = [moment, moment]
// check with start time and end time
if (start_date <= unavailabletime[0] && end_date >= unavailabletime[1]) {
is_conflict = true
}
});
if(is_conflict) {
$('#message').text("Cannot overlap existing bookings!");
$('#preview').hide();
$('#btn_book').attr('disabled', true);
} else {
var total = duration/60 * <%= #parking.price %>;
$('#message').text("");
$('#preview').show();
$('#btn_book').attr('disabled', false);
$('#reservation_hours').text(duration/60);
$('#reservation_total').text(total);
}
}
});
arrValue on itself works and it returns the database entries but adding the .(x) i.e start_date or end_date.
This is my console for arrValue
What could be the cause of this? What I am trying to do is setup a booking system that does not allow overlapped booking down to the hour. I am trying to retrieve the time interval between start_date and end_date. Push it into unavailabletimes to find conflict. I am new to coding so I apologize if its a little messy.

Related

How to make countdown instaed of count up

I have this code that displays the timer for the exam. Which made by the admin side. the timer is counting the time in count up but i want to make it display in countdown. Unfortunately i could not figure out how to make it display in countdown.
if someone can help me i will be appreciated.
ajax.php
if(isset($_POST['subId']) && isset($_POST['userId'])){
$subId = $_POST['subId'];
$id = $_POST['userId'];
require_once('../admin/inc/db.php');
$subQuery = "SELECT * FROM subject WHERE id = '$subId' AND exam = 'on' ";
$subRun = mysqli_query($con, $subQuery);
if(mysqli_num_rows($subRun) > 0){
$subRow = mysqli_fetch_array($subRun);
$time = $subRow['time'];
$query = "SELECT * FROM timer WHERE user = '$id' AND subject = '$subId' ";
$run = mysqli_query($con, $query);
if(mysqli_num_rows($run) == 0){
$insert = "INSERT INTO timer(user, subject, spent) VALUES('$id', '$subId', 1)";
$insertRun = mysqli_query($con, $insert);
} else{
$row = mysqli_fetch_array($run);
$spent = $row['spent'];
if($spent < $time){
$count = $spent + 1;
$update = "UPDATE timer SET spent = '$count' WHERE user = '$id' AND subject = '$subId' ";
$updateRun = mysqli_query($con, $update);
echo $count;
} else{
echo "Time out!";
}
}
} else{
echo "Time out!";
}
timer.js
$(document).ready(function(){
var subId = $('#subId').val();
var userId = $('#userId').val();
var myVar = setInterval(myTimer, 1000);
function myTimer(){
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { subId: subId, userId: userId },
success: function(res) {
if(res == 'Time out!'){
clearInterval(myVar);
$('#timer').html('Time over!');
$('#exampleModal').modal({
backdrop: 'static',
keyboard: false
});
} else{
var time = res;
if(time < 60){
$('#timer').html('0:' + time);
} else if(time == 60){
$('#timer').html('1:00');
} else{
var min = Math.floor(time/60);
var sec = time % 60;
if(min < 10 && sec < 10){
$('#timer').html(min + ':' + '0' + sec);
} else if(min >= 10 && sec < 10){
$('#timer').html(min + ':' + '0' + sec);
} else{
$('#timer').html(min + ':' + sec);
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
if(jqXHR){
$('#timer').html('<span class="animated flash infinite">Exam Paused!</span>');
}
}
});
}
});
To make the timer countdown instead of counting up, you need to change the way the time variable is calculated in the success function of the AJAX request. Instead of subtracting the current time from the start time, you need to subtract the start time from the maximum time and display the remaining time.
Here's an updated version of the code that should count down:
$(document).ready(function(){
var subId = $('#subId').val();
var userId = $('#userId').val();
var totalTime = 60; // or whatever maximum time you want to set
var remainingTime = totalTime;
var myVar = setInterval(myTimer, 1000);
function myTimer(){
$.ajax({
type: 'POST',
url: 'inc/ajax.php',
data: { subId: subId, userId: userId },
success: function(res) {
if(res == 'Time out!'){
clearInterval(myVar);
$('#timer').html('Time over!');
$('#exampleModal').modal({
backdrop: 'static',
keyboard: false
});
} else{
remainingTime = totalTime - res; // calculate remaining time
if(remainingTime < 0){
remainingTime = 0; // prevent negative values
}
var min = Math.floor(remainingTime/60);
var sec = remainingTime % 60;
var timeStr = min + ':' + (sec < 10 ? '0' : '') + sec; // format time string
$('#timer').html(timeStr); // display remaining time
}
},
error: function(jqXHR, textStatus, errorThrown){
if(jqXHR){
$('#timer').html('<span class="animated flash infinite">Exam Paused!</span>');
}
}
});
}
});
Note that this code assumes that the maximum time is known and fixed, and that the >res variable returned by the AJAX request represents the time elapsed since the >start of the exam. You may need to adjust the code if these assumptions don't hold >for your use case.

how to generate datepicker bootstrap datesDisabled dynamically

i am trying to generate dynamically the disabled dates using ajax call , and pass the result to datesDisabled option of bootstrap datepicker , or for other alternative pass the result to beforeShowDay option , but it doesn't work for dynamically created array Result, but it worked fine for hard coded array.
In fact , when i use dynamically generated Array , the Date Array is passed to beforeShowDay in the second time i choose dates from datepicker, and it is not passed to the picker in the first time,
but when hard coded, the array is perfectly passed to beforShowDay from the first time the picker is clicked.
the dynamically created array is
Date Array:
2021-03-17,2021-03-18,2021-03-24,2021-04-06,2021-04-07,2021-04-13,2021-04-14
so what am doing wrong?
<script type="text/javascript">
$(document).ready(function () {
function GetHolidayOrStopDay() {
// alert("Get Holidays");
var DateArray = new Array();
$.ajax({
type: "POST",
url: "timeObjectWebService.asmx/GetHolidaysAndDisabledDays",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var JsonObject = JSON.parse(data.d);
$(JsonObject).each(function (index, da) {
var testJsonDate = formatJsonDate(da.HolidayDate);
var options = {
year: "numeric",
month: "numeric",
day: "numeric",
};
var result = testJsonDate.toLocaleDateString("en", options);
result = new Date(result);
var DateResult = formatDate(result);
//if (index < (JsonObject.length - 1)) {
DateArray.push(DateResult);
// }
// else {
// DateArray += DateResult;
//}
console.log("rrr : " + DateResult);
});
//DateArray += ']';
console.log("Date Array :" + DateArray);
//console.log("1 : " + DateArray[1]);
},
error: function (err) {
//alert("test err");
console.log(err);
},
});
//alert(DateArray);
TestdisabledDays = DateArray;
return DateArray;
}
function formatJsonDate(jsonDate) {
var dat = new Date(parseInt(jsonDate.substr(6)));
return dat;
}
var enableDays = ["2021-03-30"];
var disabledDays = [
"2021-03-23",
"2021-03-22",
"2021-03-30",
"2021-03-29",
"2021-03-28",
"2021-04-01",
]; //for this hardcoded array everything works fine
var TestdisabledDays = new Array();
TestdisabledDays = GetHolidayOrStopDay();
//GetHolidayOrStopDay();
function formatDate(d) {
var day = String(d.getDate());
//add leading zero if day is is single digit
if (day.length == 1) day = "0" + day;
var month = String(d.getMonth() + 1);
//add leading zero if month is is single digit
if (month.length == 1) month = "0" + month;
return d.getFullYear() + "-" + month + "-" + day;
}
$("#dtpicker").datepicker({
format: "dd-mm-yyyy",
autoclose: true,
startDate: "0d",
datesDisabled: [TestdisabledDays],
beforeShowDay: function (date) {
//alert("from picker");
//for disable weekends :
var dayNr = date.getDay();
if (dayNr == 0 || dayNr == 6) {
if (enableDays.indexOf(formatDate(date)) >= 0) {
return true;
}
return false;
}
if (TestdisabledDays.indexOf(formatDate(date)) >= 0) {
console.log("index of " + TestdisabledDays.indexOf(formatDate(date))); //disabledDays
console.log("TestdisabledDays = " + TestdisabledDays); //disabledDays
return false;
}
return true;
},
});
});
</script>
ajax and datepicker init are running asychronically the picker is initializing before the ajax is done(that's why it is working second time), to solve this you might consider using $.when (api.jquery.com/jquery.when) or init the datepicker then when ajax return response use the methods of the datepicker itself (bootstrap-datepicker.readthedocs.io/.../methods...) hope this helps

Ajax still executing even an error found

Good day programmers! I'am trying to submit a form then validate it using jquery with 2 ajax events. I am using ajax(timeconflict.php) for validating if there is conflict with the user's time input. but even tho it returns an error, the other ajax event is still executing(reserveroom.php). sorry for my grammar, here's my code
$('#submitreserve').click(function(){
var error=false;
var inputtimeerror = false;
var conflict = false;
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
error = true;
message ="Please Fill all required Fields!";
}
if($("#from").val()!="" && $("#to").val()!="")
{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var timeerror = false;
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH)
{
timeerror=true;
}
if(fromH == toH && fromM >= toM)
{
timeerror=true;
}
if(to == from)
{
timeerror=true;
}
if(inputFrom <= now || inputTo <= now)
{
inputtimeerror = true;
}
if(error == false && inputtimeerror == false)
{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
conflict = true;
error=true;
alert("Conflict");
return false;
}
}
});
}
if(inputtimeerror)
{
error=true;
message = "Reservation time must be higher than time today!";
}
if(conflict)
{
error = true;
message = "Conflict Time Schedule!";
}
if(timeerror)
{
message = "Invalid End Time!";
error=true;
}
}
if(error==true)
{
$("#error").text(message);
return false;
}
if(error==false)
{
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}
});
//timeconflict.php
<?php
include ('../conn.php');
// header("Content-Type: application/json");
$start_time = $_POST['startTime'];
$end_time = $_POST['endTime'];
$res_date = $_POST['inputDate'];
$res_room = $_POST['room'];
$sql = "SELECT * from tdc_reservation where ( ((`reserve_start` BETWEEN '".$start_time."' and '".$end_time."')";
$sql.= " or (`reserve_end` BETWEEN '".$start_time."' and '".$end_time."' )) or";
$sql.= " (('".$start_time."' BETWEEN `reserve_start` and `reserve_end`) or ";
$sql.= " ('".$end_time."' BETWEEN `reserve_start` and `reserve_end`)) or ";
$sql.= " ((`reserve_start` = '".$start_time."' ) or (`reserve_end`='".$start_time."' ))";
$sql.= " or ((`reserve_start` = '".$end_time."') or (`reserve_end` = '".$end_time."')) )";
$sql.= " and reserve_date='".$res_date."' and reserve_room = '".$res_room."' LIMIT 1 ";
$result = mysql_query($sql,$con);
$stack = array();
while($row = mysql_fetch_array($result))
{
$stack[] = $row;
}
$json = json_encode($stack);
mysql_close();
echo $json;
?>
I really hope someone would help me, this error already ate 2 days of my life :(
Modified your code, hope this will work
$('#submitreserve').click(function(){
var message="";
var to="";
var from="";
var fromH="";
var fromM="";
var toH="";
var toM="";
var now = new Date();
if($("#datetimepicker").val()=="" || $("#trtitle").val()=="" || $("#from").val()=="" || $("#to").val()=="")
{
message ="Please Fill all required Fields!";
}else{
from = $("#from").val(); // start time
to = $("#to").val(); // end time
fromH = from.substr(0,2); // get hour from start time
fromM = from.substr(3,2); // get mins from start time
toH = to.substr(0,2); // get hour from end time
toM = to.substr(3,2); // get mins from end time
var inputDate = $("#datetimepicker").val(); // date
inputFrom = new Date(inputDate+" "+from); // time and start date
inputTo = new Date(inputDate+" "+to); // time and end date
if(fromH > toH || (fromH == toH && fromM >= toM) || to == from)
{
message = "Invalid End Time!";
}
else if(inputFrom <= now || inputTo <= now)
{
message = "Reservation time must be higher than time today!";
}else{
$.ajax({
type:'post',
url: 'timeconflict.php',
data: { startTime : from,
endTime : to,
inputDate : inputDate,
room : target },
dataType: 'json',
success : function(e)
{
if (e.length == 0)
{
console.log("No value returned");
reserveRoom();
}
else
{
console.log(e[0]);
console.log("Conflict time schedule!");
alert("Conflict");
return false;
}
}
});
}
}
alert(message);
});
function reserveRoom(){
$.ajax({
type:'post',
url: 'reserveroom.php',
data: { trtitle : $("#trtitle").val(),
from : $("#from").val(),
to : $("#to").val(),
datetimepicker : $("#datetimepicker").val(),
ninjaday : $("#ninjaday").val(),
ninjaroom : $("#ninjaroom").val() },
dataType: 'json'
});
}

passing current timer's timing to the next page

How would i pass my current timer's timing into the next page?
Timer code
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds()/10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds: seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds: milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
I'm using
<h3 style="color: #ff0000; margin: 0; padding: 0; font-size: 100%;font-weight:normal; font-family: robotolight;"> You have <div id="timer"></div> to complete the game!
in my html.
Is there a way to pass div id='timer'> into the next page?
Thanks.
Reloading the page or loading a new page means reloading javascript since it is runs in the context of the current page. There is good way to pass along javascript variables to a new page; it requires some form of data persistence. Cookies and localStorage are two of the most common ways of persisting data client-side.
Client cookies are written to the browser cache and are transparent in HTTP headers. LocalStorage is a newer mechanism but well supported, allowing up to 5MB of browser storage without passing in headers.
In your use case, instead of storing the timer it would probably make sense to store the timestamp when the timer was started. That way it can be recalculated in the next page from this one static start value.
var timerStart;
var expireDate = new Date();
function displayTimer(){
var now = new Date().getTime();
var timerStart = timerStart || cookieTimer();
val timeDiff = now - timerStart;
document.getElementById("timer").innerHTML = timeDiff.toString();
if(timeDiff > expireDate.getTime()) clearInterval(timerInterval);
}
val timerInterval = setInterval(displayTimer, 1);
// Using cookies
function cookieTimer(){
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, expireDate) {
var d = new Date();
d.setTime(d.getTime() + expireDate.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var timerCookie = getCookie("timer");
if(timerCookie !== "") return new Date(timerCookie).getTime());
else {
setCookie("timer", timerStart, expireDate);
return new Date().getTime();
}
}
// Using localStorage
function localStorageTimer(){
function setLocalStorageObject(key, obj, expireDate){
obj.expires = expireDate.getTime();
localStorage.setItem(key, JSON.stringify(obj));
}
function getLocalStorageObject(key){
val item = localStorage.getItem(key);
if(item) return JSON.parse(item);
else return {};
}
var timerLocal = getLocalStorageObject("timer");
var now = new Date().getTime();
if(timerLocal && timerLocal.startTime && timerLocal.expires > now) return timerLocal.startTime;
else {
setLocalStorageObject("timer", { startTime: now });
return now;
}
}

How to use a variable as key in json array in javascript

I have following json formate
"[{"tempId":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"
In above format tempId is not a String-value it is a variable.It's value is something like "25Dec2013".But it is inserted as it is mean a name of variable and not a value.
So it should look like
"[{"tempId":[{"25Dec2013":"London"},{"weather":"overcast clouds"}]}]"
I have done following code.I have written one comment in code where the actual problem is.
var arrCityrecordForADay = [];
function getWeatherDataForCities(cityArray, callback) {
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24 * 60 * 60);
for (var i in cityArray) {
for (var j = 1; j <= 2; j++) {
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q=" + cityArray[i] + "&dt=" + toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrCityRecordForDay = [];
arrCityRecordForDay.push({
"cityName": data.list[0].city.name
}, {
"weather": data.list[0].weather[0].description
});
var tempId = data.list[0].city.name+""+timeConverter(data.list[0].dt);
arrCityrecordForADay.push({
tempId: arrCityRecordForDay // Here tempId is inserted as "tempId" not its value
});
if (((arrCityrecordForADay.length)) === cityArray.length) {
callback(arrCityrecordForADay);
}
}
});
toDaysTimestamp = toDaysTimestamp - (24 * 60 * 60);
}
}
}
$(document).ready(function () {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "london";
var result = document.getElementById("msg");
getWeatherDataForCities(cityArray, function (jsonData) {
var myJsonString = JSON.stringify(jsonData);
console.log(myJsonString);
});
});
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
var time = date+''+month+''+year;
return time;
}
How to insert a variable as a key in above example?
EDIT:
And Why output is not stable.Some time wrong and sometime correct.
Here is correct output:
"[{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"London22Dec2013":[{"cityName":"London"},{"weather":"overcast clouds"}]}]"
Some times it shows following output after some refresh.
"[{"Pune24Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]},{"Pune25Dec2013":[{"cityName":"Pune"},{"weather":"Sky is Clear"}]}]"
How to overcome this?
Your response will be appriciated !!
You have to use a temp variable to achieve this:
var obj = {};
obj[tempId] = arrCityRecordForDay;
arrCityrecordForADay.push(obj);

Categories

Resources