Ajax Call too late... Giving result after 15 seconds - javascript

I have jquery datepicker which gives the events list when selected date through ajax call from database.. when i click on the date the result is getting displayed too late after 15 seconds...can any 1 suggest me what to do to get the result on clicked fastly:-
var x = '';
$('#calendar').datepicker({
altField: '#datepicker_send',
inline: true,
firstDay: 1,
showOtherMonths: true,
altFormat: "yy/mm/dd",
dateFormat: "yy/mm/dd",
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
onSelect: function (dateText) {
$('#event-date').text(dateText)
x = dateText;
//alert(x);
$.ajax({
type: "GET",
url: 'check_events.php',
data: 'y=' + x,
success: function (data) {
$('#event-date1').html(data); //Alert Data on success not result.
// alert(data);
}
});
}
});
Check_events.php:-``
<? php
if (isset($_GET['y'])) {
$y = $_REQUEST['y'];
$sql_check = mysql_query("SELECT * FROM events WHERE date='$y'");
$res = mysql_num_rows($sql_check);
if ($res == 0)
{
echo '<div class="evnt_name"><a href="#">No Events For Today <a/> </div>';
} else
{
while ($rec = mysql_fetch_assoc($sql_check))
{
?>
< div > Some Result < /div>
<?php }
}
}
exit; ?>

i think #JLevett is suggesting to change your host name from localhost to 127.0.0.1 in mysql connection string. Also specify field name in select query rather than * , it is in not much of a performance improvement but it will help.

Related

FlatPickr - Get the Sundays between a date range for a calendar (inclusive)

I'm using flatPickr (a calendar plugin) to accomplish this. I'm sending the minDate and maxDate, which are both always Sundays, to the JavaScript from a PHP function:
$("#weeklySelector").flatpickr(
{
inline: true,
enableTime: false,
dateFormat: "Y-m-d",
minDate: "<?php echo getSecondSunday($oldestDay[0], $newestDay[0]); ?>",
maxDate: "<?php echo getLastSunday($newestDay[0], getSecondSunday($oldestDay[0], $newestDay[0])); ?>",
defaultDate: "<?php echo getLastSunday($newestDay[0], getSecondSunday($oldestDay[0], $newestDay[0])); ?>",
enable: [
function(date) {
// Enable only the Sundays between the minDate and maxDate
// Include the minDate & maxDate because they both always will be Sundays
}
],
onChange: function(selectedDates, dateStr, instance) {
weeklyDate = dateStr;
},
});
In pseudo-code, the logic looks something like this:
// minDate = "2020-04-05";
// maxDate = "2020-04-26";
enable: [
function(date) {
minDate, while(minDate+7 <= maxDate);
// Output: "2020-04-05", "2020-04-12", "2020-04-19", "2020-04-26"
}
],
Link to docs: https://flatpickr.js.org/examples/#disabling-all-dates-except-select-few
You need to use the .getDay() method of the date, which returns the day of the week (0 is sunday).
enable:[
function(date) {
return date.getDay() === 0; // 0 is sunday
}
]

Setting up Pickadate 'onSet'

I'm trying to setup pickadate on two inputs.When a date is selected on the first input, i would like to set the selected date in the second input if the 2nd is empty.
First I tried to update the value after the first input is selected but something doesn't work correclty.
The configuration of both input is complexe so i would like to do it this way :
$( '#event-begin-date,#event-end-date' ).pickadate({
min: true,
max: undefined,
today: '<?php echo T_("Aujourd\'hui"); ?>',
clear: '<?php echo T_("Effacer"); ?>',
close: '<?php echo T_("Fermer"); ?>',
format: '<?php echo T_("dd/mm/yyyy"); ?>',
firstDay: <?php echo T_("1"); ?>,
formatSubmit: '<?php echo T_("dd/mm/yyyy"); ?>'
});
$('#event-begin-date').pickadate({
onSet: function(thingSet) {
var picker = $input.pickadate('picker');
picker.set('select', this.component.item.select.pick );
}
});
Amsul, the creator of this plugin has made a codepan example for this case: pickadate v3: “from” & “to” dates.
this is the code incase codepen is unavailable:
var from_$input = $('#input_from').pickadate(),
from_picker = from_$input.pickadate('picker')
var to_$input = $('#input_to').pickadate(),
to_picker = to_$input.pickadate('picker')
// Check if there’s a “from” or “to” date to start with.
if ( from_picker.get('value') ) {
to_picker.set('min', from_picker.get('select'))
}
if ( to_picker.get('value') ) {
from_picker.set('max', to_picker.get('select'))
}
// When something is selected, update the “from” and “to” limits.
from_picker.on('set', function(event) {
if ( event.select ) {
to_picker.set('min', from_picker.get('select'))
}
else if ( 'clear' in event ) {
to_picker.set('min', false)
}
})
to_picker.on('set', function(event) {
if ( event.select ) {
from_picker.set('max', to_picker.get('select'))
}
else if ( 'clear' in event ) {
from_picker.set('max', false)
}
})
For propose solution, pay attention of double declaration of .pickadate() :
var from_$input = $('#input_from').pickadate(),
from_picker = from_$input.pickadate('picker');
First line will redeclare without any customization which could lead to issue in your code.
A more consise way to proceed using event, and adding data-from or data-to in your input :
When you open the modal, event check if there is value in from/to and set on the fly the max/min value
var from = $(this).data('from'),
to = $(this).data('to');
$(this).attr('data-value', $(this).val()).pickadate({
min: true,
selectMonths: true,
selectYears: 3,
format: 'dd mmm yyyy',
formatSubmit: 'yyyy-mm-dd',
hiddenName: true,
onOpen: function() {
if(typeof from !== 'undefined' && $('#' + from)) {
var value = ($('#' + from).val() === '' ? true : $('#' + from).pickadate('picker').get('select'));
this.set('min', value);
} else if(typeof to !== 'undefined' && $('#' + to)) {
var value = ($('#' + to).val() === '' ? false : $('#' + to).pickadate('picker').get('select'));
this.set('max', value);
}
}
});

Bootstrap datepicker beforeShowday works only on first change

I'm trying to disable booked dates on datepicker. My code simply posts an ID to ajax.php file and i run a mysql query based on that id and get start and end dates. then i make an array that contains these dates and the ones in between. Finally I get this json_encoded array and it basically defines dates to be disabled on my bootstrap datepicker. I have recently found out that nothing is wrong with $.post method and changed the title. The problem was beforeShowday, it doesn't rerun after changes. Here is the jQuery code:
$.ajaxSetup({ cache: false });
var date = new Date();
date.setDate(date.getDate());
function getJsonRes(urlid){
var tarihler = [];
var url="ajax.php";
$.post( url, {"id":urlid}, function(data) { //this is the post request
$.each( data, function(key, val) { //to retrieve json encoded data
var tarih=val;
tarihler.push(tarih);
});
var disabledDays = tarihler;
function daysDisabled(date) {
for (var i = 0; i < disabledDays.length; i++) {
if (new Date(disabledDays[i]).toString() == date.toString()) {
return false;
}
}
return true;
}
$('#grs').datepicker({ //this is start date
language:'tr',
todayHighlight:true,
weekStart: 1,
startDate:date,
autoclose: true,
format: 'dd-mm-yyyy',
beforeShowDay: daysDisabled
})
.on('changeDate', function (selected) {
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf()))+1);
$('#cks').datepicker('setStartDate', startDate);
});
$('#cks').datepicker({ //this is end date
todayHighlight:true,
weekStart: 1,
language:'tr',
autoclose: true,
format: 'dd-mm-yyyy',
beforeShowDay: daysDisabled
})
.on('changeDate', function (selected) {
FromEndDate = new Date(selected.date.valueOf());
FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
$('#grs').datepicker('setEndDate', FromEndDate);
});
}, "json");
}
$('#choice').change(function(){
var idvalue=$(this).val();
getJsonRes(idvalue);
});

Validation in Java script for the date in asp.net

I have java script in which i have to do validation for date i.e todate >= fromdate.
Below is my script. I need to validate the dates so that user will select the Fromdate-Todate. Thanks in advance.
// <reference path="http://localhost:5378/Scripts/jquery-1.4.1-vsdoc.js" />
var pubReportName = "";
/* Dom loaded function */
$(function () {
pubReportName = "";
$("#bttnPrint").click(PrintReport_Click);
$('#txtFrDate').val('');
$('#txtToDate').val('');
$("#txtFrDate").datepicker({ dateFormat: 'dd/mm/yy' });
$("#txtToDate").datepicker({ dateFormat: 'dd/mm/yy' });
$('#ReportLeftDiv li').click(function () {
// remove all active classes
$('#ReportLeftDiv li').removeClass('active');
$(this).addClass('active');
});
});
function PrintReport_Click() {
var repName = $('#ReportLeftDiv li.active').attr('id');
if (repName == undefined || repName == null) {
alert("Please choose the Report name");
return false;
}
var ReportParameters = new Array();
var StDt = $('#txtFrDate').val();
var EndDt = $('#txtToDate').val();
ReportParameters.push({ ReportName: "/LISReportProject/" + repName, ParaName: "pStartDate", ParaValue: StDt });
ReportParameters.push({ ReportName: "/LISReportProject/" + repName, ParaName: "pEndDate", ParaValue: EndDt });
sessionStorage.setItem('ReportParameters', JSON.stringify(ReportParameters));
// ShowHideProcessingDivs('SHOW');
fnPrintResult();
var data1 = JSON.stringify({ ReportParameters: ReportParameters });
$.ajax({
cache: false,
type: "POST",
url: "WCF/LabStatusService.svc/SetSessionValues",
data: data1,
contentType: "application/json; charset=utf-8",
dataType: "json",
processType: false,
success: fnPrintResult,
failure: onErrorFunction
});
}
function fnPrintResult()
{
$.PrintPreview("LAB Statistics Report", "../PrintPreview.aspx");
}
function onErrorFunction(result) {
//document.getElementById('divWait').style.visibility = "hidden"
//ShowHideProcessingDivs('SHOW');
PopupMessage("Error", result.d, 'Alert');
}
function ShowHideProcessingDivs(ShowHide) {
switch (ShowHide) {
case 'SHOW':
$('#divWait').removeClass('#overlay').addClass('').show();
if ($('#Processing').hasClass("Processing"))
$('#Processing').removeClass("Processing");
$('#Processing').addClass("Processing").show();
break;
case 'HIDE':
$('#divWait').hide();
$('#Processing').hide();
break;
}
}
Fiddle
Javascript
$('#txtFrom').datepicker({
inline: true,
dateFormat: 'dd/mm/yy'
});
$('#txtTo').datepicker({
inline: true,
dateFormat: 'dd/mm/yy'
});
function com() {
var start = $('#txtFrom').val();
var to = $('#txtTo').val();
if (new Date(to) >= new Date(start)) {
$('#result').text("To date is greater than or equal to start");
}else{
$('#result').text("To date is less than to start");
}
}
There are two alternates.. Either the user might be forced to select the to date greater than or same as from date directly by using jQuery onclosed function within datepicker and other is by using javascript Date object

send jquery var to php in my code

.js code is loaded on index.php load. I want to send [date var] to php
$(function() {
$('#datepicker').datepicker( {
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
showButtonPanel: true,
numberOfWeek: 0,
dateFormat: 'yy-mm',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
var date = year +'-'+month;
var newDate = new Date(year, month, 1)
$(this).datepicker('setDate',newDate);
}
});
});
You can place whatever you want to send in reqObject. You can access this object in you php code as the requestBody.
Call back is the function you want to execute after you get response from the server.
url is noting but the url to which you are posting your data
var reqObject = {"newDate":newDate}
var type = 'POST'
var url = "your post url"
var callback = function(data){
console.log(data)
//Your code goes here
}
sendData(type,reqObject,url,callBack);
sendData: function(type,reqObject,url,callBack) {
$.ajax({
type: type,
data: reqObject ,
dataType: "json",
url: url ,
success: function(response){
callBack(response);
}
});
}

Categories

Resources