Ajax still executing even an error found - javascript

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'
});
}

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.

undefined from arrValue.start_date

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.

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

Why validation message is shown even after correcting values

I have html contact form in which i have handled validations in JS.
If there is any incorrect data/value in any field for e.g emailid, validation works correctly, but even after correcting the data it keeps popping.
Attaching the code and the screenshot for the same.
Please help.
function askfordemo() {
var path = document.URL;
var url = "";
url = new URL(path);
var frm = $(document.forms);
var formData = JSON.stringify(frm.serialize());
var name = $("#name").val();
var emailID = $("#emailID").val();
var phone = $("#phone").val();
var companyname = $("#companyname").val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(emailID)) {
return true;
} else {
$("#emailID")[0].setCustomValidity('Invalid Email Address');
return false;
}
if ($('#date1') != null && $('#date1').is(':visible')) {
var contactdate = new Date($('#date1').val());
var dateNow = new Date();
var msg = "Date cannot be less than todays date";
if (contactdate < dateNow) {
$("#date1")[0].setCustomValidity('Date cannot be less than todays date');
return;
} else if (contactdate == 'Invalid Date') {
$("#date1")[0].setCustomValidity('Please fill out this field with Date and Time');
return
} else {
$("#date1")[0].setCustomValidity("");
}
}
if (name === '' || emailID === '' || phone === '' || companyname === '' || noofemployees === null || message === '' ||
radioValue === '' || (typeof radioValue === 'undefined')) {
return false;
}
var param = new Object();
param.name = encodeURIComponent(name);
param.emailID = encodeURIComponent(emailID);
param.phone = encodeURIComponent(phone);
param.companyname = encodeURIComponent(companyname);
param.noofemployees = encodeURIComponent(noofemployees);
param.message = encodeURIComponent(message);
param.radioValue = encodeURIComponent(radioValue);
param.date1 = encodeURIComponent(date1);
param.timezone = encodeURIComponent(timezone);
var paramjson = JSON.stringify(param);
path = path.substring(0, path.lastIndexOf("/"));
$.ajax({
url: path + '/ms/askForDemo/sendMail',
type: 'POST',
data: paramjson,
dataType: "json",
contentType: "application/json",
crossDomain: 'true',
success: function(formData) {
JSON.stringify(formData)
},
error: function(x, y, z) {
alert("Internet connection is lost. Please try again later.");
}
});
}

what can I do to prevent xss code?

I have escaped my fields, but when I make an xss code like <script>alert(one frame);</script> then the table which is specially for display the date the xss code is sent it to my database. I want when I make my own xss code dont send the JS script to my database.
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
my controller
case 'add_product':
if(isset($_POST['code']) && $_POST['code']!= '' && isset($_POST['product']) && $_POST['product']!= '' && isset($_POST['sale_type']) && $_POST['sale_type']!= '' && isset($_POST['purchase_price']) && $_POST['purchase_price']!= 0 && isset($_POST['sale_price']) && $_POST['sale_price']!= 0 && isset($_POST['min_stock']) && $_POST['min_stock']!= '' && isset($_POST['max_stock']) && $_POST['max_stock']!= '' ){
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
$newProduct = new product();
if($newProduct->add($code,$product,$sale_type,$purchase_price,$sale_price,$min_stock,$stock)){
echo "success";
}else{
echo "it cannot be added";
}
}
else{
echo "something went wrong";
}
break;
my javascript function
function addProduct(){
var code = $('#code').val();
var product = $('#product').val();
var sale_type = $('#sale_type').val();
var purchase_price = $('#purchase_price').val();
var sale_price = $('#sale_price').val();
var min_stock = $('#min_stock').val();
var max_stock = $('#max_stock').val();
var valCheck = verificar();
if(valCheck == true){
$.ajax({
url: '../controller/product_controller.php',
type: 'POST',
data: 'code='+code+'&product='+product+'&sale_type='+sale_type+'&purchase_price='+purchase_price+'&sale_price='+sale_price+'&min_stock='+min_stock+'&max_stock='+max_stock+'&boton=add_product',
}).done(function(ans){
if(ans == 'success'){
$('#code,#product,#purchase_price,#sale_price').val("");
$('#sale_type').val('0');
$('#min_stock,#max_stock').val('0');
$('#success').show().delay(2000).fadeOut();
searchProduct('','1');
}else{
alert(ans);
}
})
}
else {
}
}
XSS code in database
datable
While displaying data from database, use htmlspecialchars() function.

Categories

Resources