Bootstrap datepicker beforeShowday works only on first change - javascript

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

Related

Run a method in controller according to datepicker value

I want run the method Index in the Home Controller according to the date selected in datepicker,
Here is my View code:
<input type="text" name="date" class="datepicker" id="calendar" />
$("#calendar").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (date, instance) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home")/' + date,
success: function (data) {
if (data.success) {
alert(date)
}
}
})
}
}).datepicker("setDate", new Date());
I want when I choose a date in my datepicker run this Method:
[Route("Home/{date?}")]
public ActionResult Index( DateTime? date = null)
the problem is the Ajax call this URL: Home\12-04-2018when I choose the 12-04-2018 instead of /Home/Index/12-04-2018 is my code wrong or am I missing something? thanks for help.
Update your code as below, this should work for you. Date has been passed as query string
Script
$("#calendar").datepicker('setDate', 'today');
$("#calendar")
.datepicker({ dateFormat: 'dd/mm/yy' })
.on("changeDate", function (e) {
$.ajax({
type: "GET",
url: '#Url.Action("Index","Home") + '?date='+ e.date,
success: function (data) {
if (data.success) {
alert(e.date)
}
}
});
});
And action method:
[HttpGet]
public ActionResult Index( DateTime? date = null)
Update:
To change the date format in view, build new date string from date object that C# can parse
var newDate = e.date.getUTCMonth() + 1 + '/' + e.date.getUTCDate() + '/' + e.date.getUTCFullYear() + ' 00:00:00';
and pass it as parameter to controller.

How to format yy-mm-dd datepicker post to php?

I have javascript jquery-ui datepicker library based function for selecting from_date - to_date range and post to php. Format is posted to php as:
Wed May 13 2015 00:00:00 GMT+0200 (Central European Summer Time)
How can I set format for example 2015-05-20 for datepicker post to php in my function?
function updateResults() {
$.getJSON('results.php', {
from_date: fromDate.datepicker('getDate').toString(),
to_date: toDate.datepicker('getDate').toString()
}, function(data,status, xhr) {
$.plot('#flotcontainer', data, options);
});
}
//create a couple of date textboxes
$.datepicker.setDefaults
({
dateFormat: 'dd/mm/yy', defaultDate: '-1w', changeMonth: true, changeYear: true,
maxDate: 0, showButtonPanel: true, showWeek: true
});
var fromDate = $('#from').datepicker
({
onSelect: function()
{
var option = this.id == 'from' ? 'minDate': 'maxDate';
toDate.not(this).datepicker('option', option, $(this).datepicker('getDate'));
updateResults(); // When a new date is selected update the results
}
});
var toDate = $('#to').datepicker
({
onSelect: function()
{
updateResults(); // When a new date is selected update the results
}
});
//Set the default from and to dates.
fromDate.datepicker('setDate', '-1w');
toDate.datepicker('setDate', '+0');
updateResults(); // Initial call on load
});
Format is posted to php as:
Wed May 13 2015 00:00:00 GMT+0200 (Central European Summer Time)
Make a timestamp from it first:
$ts = strtotime($_POST['date']);
How can I set format 2015-05-20 for datepicker post to php in my function?
With the timestamp, you can use date:
$date = date("Y-m-d", $ts);
You have to use $.datepicker.formatDate(); to convert dates.
Example:
var date = $('.datepicker').datepicker('getDate');
var convertedDate = $.datepicker.formatDate('dd-mm-yy', date);
So your function would become
function updateResults() {
var from_date = fromDate.datepicker('getDate');
var to_date = toDate.datepicker('getDate');
from_date = $.datepicker.formatDate('yy-mm-dd', from_date);
to_date = $.datepicker.formatDate('yy-mm-dd', to_date);
$.getJSON('results.php', {
from_date: from_date,
to_date: to_date
}, function (data, status, xhr) {
$.plot('#flotcontainer', data, options);
});
}
For a live example check this JSfiddle
EDIT:
Use $.datepicker.formatDate('yy-mm-dd', ..); to convert dates. I changed my answer and provided a JSfiddle

Javascript error when trying to create a calendar

I'm brand new to javascript and php and having a slight problem.
I'm trying to create a php calendar that interacts with mysql database and have been trying to write some javascript to add events to the calendar.
My events are being brought from the mysql database but whenever I click to add an event to the calendar I get an error in the console saying "uncaught TypeError: undefined is not a function" which appears to be caused by these lines in the code:
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
My code is below, console log 'testing function success' is not being displayed. Please help!
$(document).ready(function() {
//get current date
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
theme:true,
weekNumbers: true,
//allow a 'more' option if too many events.
eventLimit: true,
//enables agenda view
header:{
left:'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'event.php',
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
console.log('testing function 1');
var title = prompt('Event Title:');
if (title) {
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'eventadd.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json) {
console.log('testing function success');
alert('OK');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
});
});
Instead of lines
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
use (take care not to redefine local varialbes start, end, which are params of the function, also use Moment's format function according to: http://momentjs.com/docs/#/displaying/format/ as recommended by the fullCalendar v2 code migration):
var sfmated = start.format("yyyy-MM-dd HH:mm:ss");
var efmated = end.format("yyyy-MM-dd HH:mm:ss");
a working jsfiddle is here:
http://jsfiddle.net/xv5n1wod/12/

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