send jquery var to php in my code - javascript

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

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.

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

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

JS: Changing variable wont apply on next

I have this:
$('#albumPhotoNext').live('click', function () {
var currentDate = '<?php echo $grab["date"]; ?>';
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
I want to set currentDate for the r.date, on success, so next time you click on #albumPhotoNext, the currentDate is the r.date.
Right now it gives me the $grab["date"]; when i click, no matter if i did set the currentDate to r.date or not.
I only want to have $grab["date"]; as "default" if it hasnt been set to r.date
How can I do this?
currentDate is a local variable, so its value gets reset every invocation.
You will need to make the variable exist in an outer scope for your changes to persist.
The easy way of doing this:
$(function() {
var currentDate = '<?php echo $grab["date"]; ?>';
$('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { 'currentDate' : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
});
You have to define currentDate in a scope that is reachable from the scope you want to use it. Currently, currentDate is local to the event handler, so only the code inside the event handler can see the value and it gets reassigned to $grab["date"] every time the handler is called.
Define it in some scope above, e.g. in the document ready handler:
$(function() {
var currentDate = '<?php echo $grab["date"]; ?>';
$('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
currentDate = r.date;
}
});
});
});
I would approach this in a slightly different way. Instead of assigning "currentDate" to a variable, just use another jQuery selector to set the current date on the page itself.
$.('#albumPhotoNext').live('click', function () {
$.ajax({
url: "photo.php",
type: "post",
data: { currentDate : currentDate },
success: function(r){
$.('#dateOnPage').html(r.date);
}
});
});

Categories

Resources