I'm trying to make a function in jquery which checks if a given date is a holiday according to my database. I have created the function:
IsAHoliday(date)
Here is my code:
function IsAHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
async: false,
data: dataString,
success: function(r)
{
return r;
}
});
}
With this code i can't execute something like
if(IsAHoliday(date)) {
How could i achieve this ?
EDIT: Here is my datumPraznik.php
<?php
include_once('db-config.php');
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum=:datum');
$stmt->execute(array(':datum'=>$datum));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0)
{
$praznik = true;
}
else
{
$praznik = false;
}
echo $praznik;
?>
So what you could do get your PHP to return JSON so you can handle it with AJAX success function.
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum='.$datum);
$stmt->execute();
if($stmt->fetchColumn() > 0){
$praznik = true;
} else {
$praznik = false;
}
return json_encode(array('praznik' => $praznik));
And your AJAX would be
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
console.log('This is a holiday');
} else {
console.log('This is not a holiday');
}
});
So your updated function would be:
function isHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var data = 'action='+ datum;
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
return true;
} else {
return false;
}
});
}
And use it as:
if(isHoliday(date) === true) {
// do something
}
First, PHP needs to return JSON, so change:
echo $praznik;
to:
echo json_encode($praznik);
Second, since AJAX is asynchronous (you shouldn't use async: false), your function should take callbacks:
function IsAHoliday(date, truecb, falsecb) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
data: dataString,
success: function(r)
{
if (r) {
truecb();
} else {
falsecb();
}
}
});
}
You then call it like:
IsAHoliday(date, function() {
// stuff to do on holiday
}, function() {
// stuff to do on non-holiday
});
I wasn't able to fix my problem using your solutions but i've combined them and came to this solution.
I've made a global variable (array) and called ajax which returns ALL HOLIDAY DATES and stores them in the global variable.
var prazniciArray = [];
$(document).ready(function()
{
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
dataType: 'json',
cache: false,
success: function(rez)
{
praznici = rez;
for (var i = 0; i < praznici.length; i++) {
prazniciArray.push(moment(praznici[i]));
}
$('#datetimepicker1').data("DateTimePicker").disabledDates(prazniciArray);
}
});
}
After that i could make the function:
function IsHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
if(jQuery.inArray(datum, praznici) !== -1)
{
return true
}
else
{
return false;
}
}
datumPraznik.php
<?php
include_once('db-config.php');
$stmt=$db_con->prepare('SELECT praznik_datum FROM praznici');
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$praznici = count($row);
$prazniciarray = array();
for ($i = 0; $i < $praznici; $i++) {
array_push($prazniciarray,$row[$i]["praznik_datum"]);
}
echo json_encode($prazniciarray);
?>
And my table looks like this:
praznik_id | praznik_ime | praznik_datum
-----------------------------------------
| 1 | Thanksgiving | 2017.07.01
Related
I created an ajax function that returns my items Price by fetching from my DB. I'm sure there isn't any problem with my php but sometimes I get the same result twice!
jQuery
$('.removemore___').click(function(e) {
var item_id = $(this).attr('data-item');
var col_id = $(this).attr('data-col');
var value = $(this).attr('data-value');
if ($(this).attr('data-trash') == 'trash') {
newPopuper('alert_sure__', 'flex', 'blackScreen');
$('.__aggtoyes').attr('data-item', item_id);
$('.__aggtoyes').attr('data-col', col_id);
$('.__aggtoyes').attr('data-value', value);
} else {
$.ajax({
type: "POST",
url: "includes/chekavailableitem.php?remove",
data: {
item_id: item_id,
col_id: col_id,
value: value
},
dataType: "text",
success: function(response) {
var iNum = parseInt(value);
iNum--;
if (response == 'done') {
$('.value__cart[data-item=' + item_id + '][data-col=' + col_id + ']').html(iNum);
$('.removemore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
$('.addmore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
if (iNum == 1) {
location.reload();
}
} else if (response == 'deleted') {
location.reload();
}
},
error: function() {
$('#wrong-signup').html(': 102');
},
timeout: 5000
});
}
$.ajax({
type: "POST",
url: "includes/get_finalize_cart.php",
data: {},
cache: false,
async: true,
dataType: "json",
success: function(response) {
// var final_price = $.parseJSON(response)
console.log(response);
if (response[0] == 'done') {
$('.final_price__').html(response[1] + ' <span style="font-size: .786rem;font-weight: 400">تومان</span>');
} else {
}
},
error: function() {
$('#wrong-signup').html(': 101');
},
timeout: 5000
});
e.stopImmediatePropagation();
return false;
});
Here is full function in jQuery
<?php
include 'db.php';
include 'function.php';
$user_id = extractUserId();
$chekcart = "SELECT * FROM `box` WHERE `user_id`='$user_id'";
$result_cox_cart_cheker = connectANDdie($chekcart);
$sum_price = 0;
while($row_items = mysqli_fetch_assoc($result_cox_cart_cheker)){
$price = $row_items['item_price'];
$value = $row_items['value'];
$sum_price = $sum_price + ( $price*$value );
$final_value = number_format($sum_price);
$result = ['done',$final_value];
$result1 = json_encode($result);
echo $result1;
}
and I'll also show a screenshot from console page so you can see what my result is:
You're not waiting for chekavailableitem.php?remove to complete before you call get_finalize_cart.php. Since AJAX is asynchronous, the latter might be processed first, so you'll get a duplicate of the old value.
You should put the second $.ajax() call in the sucess: function of the first $.ajax() call, or use a promise.
I have this code fragment:
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=getKey(aid); //here we trying to obtain key
if(cKey!="" && cKey!=null && cKey!=undefined){
if(isJSON(jKey) && encryption_state){
var tjKey = JSON.parse(jKey);
tjKey[aid] = cKey;
jKey = JSON.stringify(tjKey);
}else{
jKey = json.stringify({aid: cKey});
}
encryption_state=true;
}
}
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=rndstr(32); //generate string
}
var arr = {};
if(isJSON(jKey)) arr = JSON.parse(jKey);
arr[aid] = cKey;
jKey = JSON.stringify(arr);
encryption_state = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But when i call getKey(kaid) function:
function getKey(kaid){
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
return tret;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Browsers don't continue do function getKey(), they do next commands in parent function, i don't know why they ignore web server answer and don't let function return server response :(
in general, an ajax call is asynchronous. That means, a sequence like
var a = 0;
a = getAwithAjaxFromServer(...);
console.log(a);
will immediately print "0" while the ajax is still runnng.
Your entire logic with cleyand encryption_state has to be put into the done function:
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=getKey(aid);
}
}
and in your ajax:
function getKey(kaid){
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
.... PUT ALL THE LOGIC HERE .....
}
});
}
You must understand asynchronous mechanism in javascript to continue calling ajax. There are a lot of resources and stackoverflow questions. For example: https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript
So, you can convert the code so:
if(!encryption_state){
var serverKeyCallback = function(cKey) {
if(cKey!="" && cKey!=null && cKey!=undefined){
if(isJSON(jKey) && encryption_state){
var tjKey = JSON.parse(jKey);
tjKey[aid] = cKey;
jKey = JSON.stringify(tjKey);
}else{
jKey = json.stringify({aid: cKey});
}
encryption_state=true;
}
};
var localKeyCallback = function(cKey) {
if(!encryption_state){
if(cKey=="" || cKey==null){
cKey=rndstr(32); //generate string
}
var arr = {};
if(isJSON(jKey)) arr = JSON.parse(jKey);
arr[aid] = cKey;
jKey = JSON.stringify(arr);
encryption_state = true;
}
}
manageKey(cKey, aid, serverKeyCallback, localKeyCallback);
}
function manageKey(cKey, kaid, serverKeyCallback, localKeyCallback) {
if(cKey=="" || cKey==null) {
$.ajax({
method: "POST",
url: "/?mod=key&fnc=syncKey",
data: {
aid: kaid
},
done: function(data) {
var tret = (JSON.parse(data)['msg']);
serverKeyCallback(tret);
localKeyCallback(tret);
}
});
}
else {
localKeyCallback(cKey);
}
}
Defining two encapsulated pieces of code, one to execute after serverResponse, and the other to execute after the serverResponse or when you have the cKey locally stored. I haven't tested the code, but it must work as you expect.
For the following code, the emailCnt is 50 for first iteration, I need 25 in next iteration. What is the possible way to access the variable value outside the ajax success and break the for loop execution?
var limit = 50;
var emailCnt = limit;
for (var i = 0; i < 20; i++) {
console.log(emailCnt);///this value is 50 instead I need 25
if (emailCnt < limit && i != 0) {
break;
}
setTimeout(function () {
submit_post(slNo, limit, function (output) {
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
});
}, 1000);
}
function submit_post(slNo, limit, handleData) {
$.ajax({
type: 'POST',
async: false,
url: url,
data: { slNo: slNo, limit: limit },
success: function (data) { handleData(data); }
});
}
This successfully worked for me
var limit = 50;
var emailCnt = limit;
function submit_post(slNo, limit)
{
var result="";
$.ajax({
type: 'POST',
async: false,
url: url,
data: {slNo:slNo, limit:limit},
success: function(data) { result = data; }
});
return result;
}
for(var i=0;i<20;i++)
{
if(emailCnt < limit && i != 0)
{
break;
}
setTimeout(function () {
var output = submit_post(slNo, limit);
slNo = output;
emailCnt = 25;
$('#load_data').html('Hello');
}, 1000);
}
I have got this jquery/ajax
var uploaded=0;
if (uploaded!=0) {
setInterval(function() {
uploaded--;
}, 60000);
alert(uploaded);
}
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('.SubmUploadFu')[0]);
if (uploaded<=5) {
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
var json_x = $.parseJSON(data);
var classRes = json_x[0].substring(0, 1);
$(".Result").html(json_x[0]).addClass(classRes).fadeIn(500).delay(2500).fadeOut(500,function() {
$(this).removeClass(classRes);
});
$(".Posts").children(".NumberOf").html(json_x[1]);
$(".Text").val("");
$("#Nameupload").val("");
$(".PhotShow").slideUp(500);
uploaded++;
}
});
}else{
$(".Result").html("You can upload up to 5 posts in one minute").addClass("E").fadeIn(500).delay(2500).fadeOut(500);
}
});
And this php
function isFileUploadAllowed() {
$isAllowed = true;
$timeNow = time();
$timeFrameInSeconds = 30;
$maxUploadsInTimeFrame = 5;
$firstUploadTime = $_SESSION['firstUploadTime'] ? intval($_SESSION['firstUploadTime']) : $timeNow;
$numberOfUploadsInTimeFrame = $_SESSION['numberOfUploadsInTimeFrame'] ? intval($_SESSION['numberOfUploadsInTimeFrame']) : 0;
$givenTimeFrameExpired = (($firstUploadTime + $timeFrameInSeconds) < $timeNow);
if (!$givenTimeFrameExpired) {
if ($numberOfUploadsInTimeFrame + 1 > $maxUploadsInTimeFrame) {
$isAllowed = false;
}
}
if ($isAllowed === true) {
if ($givenTimeFrameExpired) {
$_SESSION['firstUploadTime'] = $timeNow;
$_SESSION['numberOfUploadsInTimeFrame'] = 0;
}
$_SESSION['numberOfUploadsInTimeFrame']++;
}
return $isAllowed;
}
if(isset($_POST['new_post'])){
$Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
$Text=trim($Text);
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'])) {
if (isFileUploadAllowed()) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
$NotInarray=false;
}else{
$fileP_new_name="";
$NotInarray=true;
}
$Fileuploaded=true;
}
}else{
$fileP_new_name="";
$fileP=0;
$Fileuploaded=false;
$NotInarray=false;
}
$Posts=$con->query("SELECT Posts FROM user_opt WHERE Username='$NameId'");
$row=$Posts->fetch_row();
if (strlen($Text)>400) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}elseif(strlen($Text)==0 && $fileP==0){
$Res="Both fields are empty";
$PostNum=$row[0];
}elseif($Fileuploaded===true){
if ($NotInarray==true) {
$Res="Only jpg and png files are allowed";
$PostNum=$row[0];
}elseif ($fileP_error!=0) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}else{
$Res="Success";
$PostNum=$row[0]+1;
}
}else{
$Rand=generateRandomString(100);
$query=$con->query("INSERT INTO uploads (Rand,Username,image,`Text`,`Date`) VALUES('$Rand','$NameId','$fileP_new_name','$Text',NOW())");
$querya=$con->query("UPDATE user_opt SET posts=posts+1 WHERE Username='$NameId'");
$PostNum=$row[0]+1;
$Res="Success";
}
echo json_encode(array($Res,$PostNum));
}
But the problem is when user uses dev tools he can easily change
if (uploaded<=5) {
To
if (uploaded<=50) {
And jquery will take increase limit to 50.How can i prevent that?
Also may the problem be in php function?Cause if my php function works properly it should not insert data into database but it does
You have no else clause for if (isFileUploadAllowed()), so you're not clearing the variables. You can combine that test with the outer test:
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'] && isFileUploadAllowed())
This is what the code below does:
Goes to a table in a database and retrieves some search criteria I will send to Google API (the PHP file is getSearchSon.php)
After having the results, I want to loop around it, call the Google API (searchCriteriasFuc) and store the results in an array
The last part of the code is doing an update to two different tables with the results returned from Google API (updateSearchDb.php)
In my code, I am using setTimeout in a few occasions which I don't like. Instead of using setTimeout, I would like to properly use callback functions in a more efficient way (This might be the cause of my problem) What is the best way of me doing that?
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'Text',
/*data: { }, */
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
if(data != "connection")
{
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var length = search_criterias.length;
var arrXhr = [];
var totalResultsArr = [];
var helperFunc = function(arrayIndex)
{
return function()
{
var totalResults = 0;
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
}
}
}
var searchCriteriasFuc = function getTotalResults(searchParam, callback)
{
var searchParamLength = searchParam.length;
var url = "";
for(var i=0;i<searchParamLength;i++)
{
url = "https://www.googleapis.com/customsearch/v1?q=" + searchParam[i] + "&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + date_length;
arrXhr[i] = new XMLHttpRequest();
arrXhr[i].open("GET", url, true);
arrXhr[i].send();
arrXhr[i].onreadystatechange = helperFunc(i);
}
setTimeout(function()
{
if (typeof callback == "function") callback.apply(totalResultsArr);
}, 4000);
return searchParam;
}
function callbackFunction()
{
var results_arr = this.sort();
var countResultsArr = JSON.stringify(results_arr);
$.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'Text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
else resultsDiv.innerHTML = 'Update was successful';
}); //end second ajax call
}
//llamando funcion principal
var arrSearchCriterias = searchCriteriasFuc(search_criterias, callbackFunction);
}
else
{
alert("Problem with MySQL connection.");
}
}); // end ajax
});
How you did it in 2015
Callbacks are things of the past. Nowadays you represent result values of asynchronous tasks with Promises. Here is some untested code:
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
}).then(function(data) {
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
return Promise.all(search_criterias.map(function(criteria) {
return $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
});
})).then(function(totalResultsArr) {
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
return $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
}).then(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
});
}
}).then(null, function() {
alert('Some unexpected error occured: ' + e);
});
});
This is how you do it in 2016 (ES7)
You can just use async/await.
$(document).ready(async() => {
try {
var data = await $.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
});
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var totalResultsArr = await Promise.all(
search_criterias.map(criteria => $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
}))
);
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
var data2 = await $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
if(data2 == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
}
} catch(e) {
alert('Some unexpected error occured: ' + e);
}
});
UPDATE 2016
Unfortunately the async/await proposal didn't make it to the ES7 specification ultimately, so it is still non-standard.
You could reformat your getTotalResults function in the following matter, it would then search rather sequential, but it should also do the trick in returning your results with an extra callback.
'use strict';
function getTotalResults(searchParam, callback) {
var url = "https://www.googleapis.com/customsearch/v1?q={param}&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + (new Date()).getTime(),
i = 0,
len = searchParam.length,
results = [],
req, nextRequest = function() {
console.log('received results for "' + searchParam[i] + '"');
if (++i < len) {
completeRequest(url.replace('{param}', searchParam[i]), results, nextRequest);
} else {
callback(results);
}
};
completeRequest(url.replace('{param}', searchParam[0]), results, nextRequest);
}
function completeRequest(url, resultArr, completedCallback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function() {
if (this.readyState === 4 && this.status == 200) {
var totalResults = JSON.parse(this.responseText).queries.nextPage[0].totalResults;
resultArr.push(totalResults);
completedCallback();
}
};
req.send();
}
getTotalResults(['ford', 'volkswagen', 'citroen', 'renault', 'chrysler', 'dacia'], function(searchResults) {
console.log(searchResults.length + ' results found!', searchResults);
});
However, since you already use JQuery in your code, you could also construct all the requests, and then use the JQuery.when functionality, as explained in this question
Wait until all jQuery Ajax requests are done?
To get the callback execute after google calls are finished you could change:
var requestCounter = 0;
var helperFunc = function(arrayIndex)
{
return function()
{
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
requestCounter++;
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
if (requestCounter === search_criterias.length) {
callbackFunction.apply(totalResultsArr);
}
}
}
}
then remove the setTimeout on searchCreteriaFuc.
Consider using promises and Promise.all to get all much cleaner :D