How to assign Date to defaultDate? - javascript

I posted the same question but did not get the answer, so I post the question again.
Here are two global variables.
var ri_startDate = "";
var ri_endDate = "";
I added the date values stored in DB to global variables.
(The format of the date retrieved from the DB is YYY-MM-DD.)
$.ajax({
type: 'POST',
url: 'getSectionDate.do',
data: {"ri_idx" : ri_idx},
dataType: 'JSON',
success: function(resultData){
$.each(resultData, function(key, value){
ri_startDate = value.ri_startDate;
ri_endDate = value.ri_endDate;
$('#ri_startDate').val(ri_startDate);
$('#ri_endDate').val(ri_endDate);
});
if(ri_startDate != null || ri_startDate != "" || ri_endDate != null || ri_endDate != "") {
$('#calendarContainer').show(700,rerenderingFullCalendar);
$('.doctorname2').hide(700);
}
},
error: function(resultData) {
console.log("resultData Error >> " + resultData);
}
});
Now that everything is done, I'm going to insert it into the defaultDate.
As follows:
$('#calendar').fullCalendar({
defaultDate: moment(ri_startDate)
});
However, this will cause an error.
So I did the following.
$(function() {
var moment_startDate = moment(ri_startDate, 'YYYY-MM-DD');
var result_moment_startDate = moment_startDate.format('YYYY-MM-DD');
console.log(result_moment_startDate);
$('#calendar').fullCalendar({
defaultDate: moment(result_moment_startDate)
});
});
What did I do wrong?
I can not find the reason. I've tested it in Google Developer Tools, but it works fine. (When you create it globally instead of inside a function)
How can I do what I want? I just want to add the query value (ri_startDate) from the DB to defaultDate.
If you run this on Google Developer Tools, it works.
However, when I write this code and run it, I get the following error.
Uncaught TypeError: Cannot read property 'clone' of null at MonthViewDateProfileGenerator.DateProfileGenerator.buildRenderRange (fullcalendar.js:10447) at MonthViewDateProfileGenerator.BasicViewDateProfileGenerator.buildRenderRange (fullcalendar.js:12144) at MonthViewDateProfileGenerator.buildRenderRange (fullcalendar.js:14621) at MonthViewDateProfileGenerator.DateProfileGenerator.build (fullcalendar.js:10265) at MonthView.View.setDate (fullcalendar.js:3624) at Calendar.renderView (fullcalendar.js:9607) at Calendar.initialRender (fullcalendar.js:9534) at Calendar.render (fullcalendar.js:9470) at HTMLDivElement. (fullcalendar.js:12414) at Function.each (jquery-3.2.1.min.js:2)
How do I fix it? Because of this, progress can not be made.
Please help me.

As per our discussion you are sending January 2018 as the date to moment and assigning it to defaultDate and January 2018 is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.
Please refer to URL for more info. As your current problem is that you are unable to set default date to the desired one and if you provide the date in proper format as i described above you can set the calendar to any date in past or future see a demo below i am setting the calendar to 2015-10-10
$('#calendar').fullCalendar({
defaultDate: $.fullCalendar.moment('2005-10-01')
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.0/fullcalendar.print.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.0/fullcalendar.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.8.0/fullcalendar.js"></script>
<div id="calendar">
</div>

I solved this problem with the help of #Muhammad Omer Aslam.
ajax part :
$.ajax
({
type: 'POST',
url: 'getSectionDate.do',
data: {"ri_idx" : ri_idx},
dataType: 'JSON',
success: function(resultData)
{
console.log("resultData : " + resultData);
$.each(resultData, function(key, value)
{
ri_startDate = value.ri_startDate;
ri_endDate = value.ri_endDate;
var a = JSON.stringify(resultData);
$('#ri_startDate').val(ri_startDate);
$('#ri_endDate').val(ri_endDate);
});
if(ri_startDate != null || ri_startDate != "" || ri_endDate != null || ri_endDate != "")
{
loadCalendar(ri_startDate, ri_endDate);
$('#calendarContainer').show(700,rerenderingFullCalendar);
$('.doctorname2').hide(700);
}
},
error: function(resultData)
{
console.log("resultData Error >> " + resultData);
}
});
loadCalendar function part:
function loadCalendar(ri_startDate,ri_endDate)
{
var todayMomentDate = $.fullCalendar.moment(ri_startDate);
var resultTodayMomentDate = todayMomentDate.format('YYYY-MM-DD');
console.log("resultTodayMomentDate : " + resultTodayMomentDate);
// fullCalendar 관련
$('#calendar').fullCalendar
({
});
$('#calendar').fullCalendar('gotoDate', resultTodayMomentDate);
};
This all works well.

Tried something like this... I used it before on my code.
$( "#datepicker-14" ).datetimepicker({
//format : 'DD-MM-YYYY HH:mm'
viewMode: 'days',
format: 'DD/MM/YYYY'
}, "date");
var dateNow = new Date();
var date= moment(dateNow).format('DD/MM/YYYY');

Related

fooplugins/Footable - "Cannot read property 'name' of null" when trying to load the table from JSON

I want to use the plugin "FooTable" with ajax calls.
Everything works fine when I hardcode the JSON, or even load it from a JSON file with $.get('....json'). When I try to load the table content from my server, I always get the error message "Cannot read property 'name' of null" shown with details here:
Error message
The image above also shows the JSON logged into the Console. I've tried loading it in a lot of different ways (in back- and front-end), but I just cant get it to work. I left some of my tries commented out in the attached Code.
JavaScript:
$(document).ready(function () {
jQuery(function ($) {
var ft = FooTable.init('.table', {
"columns": $.get('/js/mycols.json'),
//"rows": $.get('/js/myrows.json')
"rows": $.get('/api/GetEvents', function (e) {
console.log(JSON.parse(e.value));
//ft.rows.load(JSON.parse(e.value));
}, "json")
});
//$.ajax({
// url: "/api/GetEvents",
// dataType: "json",
// type: "GET"
//}).done(function (e) {
// console.log(e);
// ft.rows.load(e.value);
//})
});
});
ASP.NET Backend:
List<JObject> objList = new List<JObject>();
foreach (var e in events)
{
JObject jObj = JObject.FromObject(new
{
name = e.Name,
veranstaltungstyp = e.Type,
startzeit = e.StartTime.ToString("H:mm - dd MMMM yyyy"),
ende = e.EndTime.ToString("H:mm - dd MMMM yyyy"),
erstelltvon = e.CreatedBy.FirstName + " " + e.CreatedBy.LastName,
render = "placeholder"
});
objList.Add(jObj);
}
var result = new JsonResult(JsonConvert.SerializeObject(objList));
result.ContentType = "json";
result.StatusCode = 200;
result.SerializerSettings = new JsonSerializerOptions();
return Json(result);
I had a similar issue. It appears that FooTable is trying to load the rows before the table has been fully rendered and so it is not able to properly access the DOM.
Try wrapping your fetch in a on('ready.ft.table').
$(document).ready(function () {
jQuery(function ($) {
var ft = FooTable.init('.table', {
"columns": $.get('/js/mycols.json'),
});
$('.table').on('ready.ft.table', function(e) {
$.ajax({
url: "/api/GetEvents",
dataType: "json",
type: "GET"
}).done(function (e) {
console.log(e);
ft.rows.load(e.value);
})
});
});
});

Cannot read property '_calendar' of undefined in moment.js

I am getting an error when someone is trying to submit an event on their calendar to be saved to the server. Any help is appreciated, thank you for your time! Please let me know if you guys are needing anymore specific information.
UPDATE: It seems that when I switched from pushing to an array myself when a event is added to the calendar via the drop feature from fullcalendar, then it works ok but I had issues with that code so I used clientevents from fullcalendar instead and now I am getting this error. Any ideas on what a fix might be for this?
I am getting the following error:
Uncaught TypeError: Cannot read property '_calendar' of undefined at D (moment.min.js:6) at e (jquery-1.11.3.min.js:5) at Vb
(jquery-1.11.3.min.js:5) at Vb (jquery-1.11.3.min.js:5) at Vb
(jquery-1.11.3.min.js:5) at Function.m.param
(jquery-1.11.3.min.js:5) at Function.ajax (jquery-1.11.3.min.js:5)
at Object. (calendar:514) at Function.each
(jquery-1.11.3.min.js:2) at Object.success (calendar:500)
companyCalendar.blade.php
var emailContainer = {};
emailContainer.email = email;
console.log("AJAX call here to submit dropped events as guest.");
$.ajax({
type: "POST",
url: '/partialAccountCheck',
data: emailContainer,
success: function (data) {
console.log('success, proceed with adding events to the company calendar');
$.each(newEvents, function (i, event) {
if (event.title !== 'undefined' && event.title !== null && event.title !== undefined) {
console.log(JSON.stringify(event));
event.start = moment(event.start).toDate();
event.end = moment(event.end).toDate();
event.start = formatDate(event.start) + ' ' + event.start.getHours() + ':' + event.start.getMinutes() + ':00';
event.end = formatDate(event.end) + ' ' + event.end.getHours() + ':' + event.end.getMinutes() + ':00';
console.log('event start is: ' + event.start);
console.log('event end is: ' + event.end);
event.identifier = <?php echo json_encode($companyIdentifier) ?>;
event.email = email;
event.services = event.title;
event.startAppointmentTime = event.start;
event.endAppointmentTime = event.end;
console.log("AJAX call here adding dropped appointments as guest.");
$.ajax({
type: "POST",
url: 'submitCalendarEvent',
data: event,
success: function (data) {
console.log('success');
},
complete: function (data) {
console.log(data);
}
});
} else {
console.log('exclude from submission');
}
});
},
complete: function (data) {
console.log(data);
}
});
I solved the problem creating variables for event.start and event.end.
start=moment(event.start).format('Y-MM-DD HH:mm:ss');
end=moment(event.end).format('Y-MM-DD HH:mm:ss');
$.ajax({
url:"insert.php",
type:"POST",
data:{title:event.title, start:start, end:end},
you need to convert your date from date format to string.
event.start = moment(event.start).format('YYYY-MM-DD HH:mm:00');
event.end = moment(event.end).format('YYYY-MM-DD HH:mm:00');

Large amount of events loaded on the angularjs-bootstrap-calendar

I'm pulling in ALL my event data from my server and since I have a lot of events to pull, the angular-bootstrap-calendar takes a lot of time to load.
I was wondering if its possible to pull only a month's worth of data for the current view I'm in (month, week, day..I would hide the year view). As I change the view to the next month, I'd pull the data for that month only.
Right now, I pull ALL the data only once, when the calendar loads, but not sure how to pull the data when the view changes.
var urlapievents = $location.protocol() + "://" + $location.host() + "/api/events/" ;
$http.get(urlapievents).success(function(events) {
Good solution for me
Get year and month of view, send it to API, and only retrieve events for that year-month:
js
vm.viewChangeClicked = function() {
var viewDateYearMonth = moment(vm.viewDate).format('YYYY-MM');
var urlapieventsall = $location.protocol() + "://" + $location.host() + "/api/events/" + viewDateYearMonth ;
$http.get(urlapieventsall).success(function(events) {
vm.events = events.events;
});
};
html
<div class="col-md-6 text-center">
<div class="btn-group">
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'month'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Month</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'week'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Week</label>
<label class="btn btn-primary" ng-model="vm.calendarView" uib-btn-radio="'day'" ng-click="vm.cellIsOpen = false; vm.viewChangeClicked()">Day</label>
</div>
</div>
I've also added logic to check if previous yyyy-mm is equal to current yyyy-mm to save some unnecessary calls to the API.
If you grab your events as a json feed, you can use additional options - startParam and endParam. They can be used like this:
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
if (request) {
request.abort();
};
$.mobile.loading('show');
request = $.ajax({
type: "POST",
url: "../Services/Calendar/CalendarService.asmx/GetEvents",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ dtStart: " + JSON.stringify(start) + ", dtEnd: " + JSON.stringify(end) + "}",
success: function(data) {
var events1 = [];
$(data.d).each(function() {
events1.push({
title: this.Title,
start: this.Start,
end: this.End,
id: this.Id
});
});
callback(events1);
$.mobile.loading('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.statusText == 'abort') {
$.mobile.loading('hide');
return;
} else {
alert('There was an error');
$.mobile.loading('hide');
}
}
});
}
});
You can read more about those parameters here: https://fullcalendar.io/docs/event_data/events_json_feed/
The functionality you describe is a sort of date pagination, although this functionality isn't built in (shame, because it sounds really useful), you can implement your own with some small amount of work
First, the datepicker stores a JS Date object inside the ng-model, you can $watch it and get the current year/month/day out of it
$scope.modelDate = new Date()
...
$scope.$watch('modelDate', function(newDate, oldDate) {
newDate.getDay(); // 5
newDate.getMonth(); // 11
newDate.getYear(); // 116
})
Now you can query your database to get all the event for your selected month
Also, you can utilize the datepicker's mode (showing wether you are viewing the datepicker in the day/month/year mode, you set it up inside the options object).
datepickerMode C (Default: day) - Current mode of the datepicker (day|month|year). Can be used to initialize the datepicker in a specific mode.
Using this property you can query a month, year or years of events.

how to pass jquery date parameters in php

Please help me.. I have the following codes..
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
});
now I want to pass the firstDate and the lastDate to a php. How should I do this. and how can I retrieve the passed value in the php. I'm not very familiar with javascripts. Hope anyone can help me. Thanks in advance.
Here is my full code..
JS tags
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap.datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
HTML
<div class="input-group" id="DateDemo">
<input type='text' id='weeklyDatePicker' placeholder="Select Week" class="form-control" />
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
JS
$("#weeklyDatePicker").datetimepicker({
calendarWeeks:true,
format: 'MM/DD/YYYY'
});
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
alert(firstDate);
$.post("SAMPLE1.php",{"fdate" : firstDate ,"ldate" : lastDate});
});
$('#DateDemo').on('dp.change', function (e) {
var kk = $("#weeklyDatePicker").val();
$("#output").html(
" Week Number: " + moment(kk, "MM/DD/YYYY").week() + " of " +
moment(kk, "MM/DD/YYYY").weeksInYear()
);
});
SAMPLE1 CODE
<?php
echo $_POST["fdate"]; //for firstdate
echo $_POST["ldate"]; //for lastdate
?>
You can use jquery for that. Try this code :
YOUR JS FILE CODE :
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("main.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
});
});
YOUR PHP FILE CODE (main.php)
<?php
if(isset($_POST["fdate"])) {
echo $_POST["fdate"]; //for firstdate
}
if(isset($_POST["ldate"])) {
echo $_POST["ldate"]; //for lastdate
}
?>
Make sure both the files are in same folder.
I would use $.ajax() function, which will let you handle the error status as well, because it is both a good practice to handle errors for the users and an indicator of what is going wrong with your script.
$.ajax({
url: 'test.php',
type: 'POST',
data: {fdate : firstDate ,ldate : lastDate},
dataType: 'text',
beforeSend: function(){
// initiate some spinner or loading infobox
// to inform the user about the AJAX request
},
success: function(response){
alert(response);
// you may use result like any standard argument
// and call or trigger other functions according to its value
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + ': ' + errorThrown);
// call some error handler or do nothing
},
complete: function(){
// close the spinner or loading box
}
});
In your PHP file, you get the variables as $_POST['fdate'] and $_POST['lDate']. Once you complete the query and get the results, echo a response something like that:
echo 'success';
or
echo 'failure';
according to the result of the query. You may use any string, not just success or failure. Just don't forget that is what you will handle in the success part of your $.ajax() function and not the error part of it. The error part is only for whatever goes wrong with the request (e.g. file not found or server error).
Well, here is the tricky part: If the only thing you want to return is a status, you may use dataType: 'text' in your $.ajax() function as I did in this example. However, if you want to return an object with some useful data, such as what has gone wrong with the PHP query or what has been accomplished by the PHP query, then you'd better to use dataType: 'json' and get a JSON response. In such a case, the end of your PHP script will change too.
$result = ['statusCode'=>1,'details'=>'Some details according to the query here'];
echo json_encode($result);
The success handler of your $.ajax() function will get an object as the argument (i.e. response will be an object) which you can use like this:
alert(response.statusCode); // will alert 1
Ajax is probably the easiest.
Javascript:
$.get("test.php", { firstDate: firstDate, lastDate: lastDate } );
or
$.post("test.php", { firstDate: firstDate, lastDate: lastDate } );
and in php
<?php
echo $_REQUEST['firstDate'];
echo $_REQUEST['lastDate'];
?>
Hi Kath Dee please check below code, I hope solve your problem using below code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#weeklyDatePicker').on('dp.change', function (e) {
// I am using test value, you can change var value base on id.
var firstDate = '08/02/2016';
var lastDate = '10/02/2016';
//$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("test.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
$("#weeklyDatePicker").val(data);
});
});
</script>
<input type="text" value="" id="weeklyDatePicker" />
test.php
<?php
// set your format as you want for display.
echo $_POST['fdate'].'-'.$_POST['ldate'];
?>
I hope this is working fine for you.

ASP.net 3.5 WebMethod Strange Behavior, jQuery AJAX receives strange data

I've ran into this strange JSON behavior.. I just cant figure out what the hell is going on..
I've got a WebMethod in my asp.net page.. It repetitively calls as page loads through jQuery AJAX.. Everything goes pretty smooth but what strange thing happens is that the data I sens to my jQuery ajax is not the SAME I just sent.. :S
here is not code of page method
[WebMethod()]
public static List<Unister.UnisterCore.Core.Domain.Comment> LoadComments(long objID, int sysID)
{
if (objID == 0)
return null;
UnisterWeb.UserControls.Presenter.CommentsPresenter _presneter;
_presneter = new UnisterWeb.UserControls.Presenter.CommentsPresenter();
List<Unister.UnisterCore.Core.Domain.Comment> comments = new List<Unister.UnisterCore.Core.Domain.Comment>();
comments = _presneter.LoadComments(sysID, objID);
if (comments.Count == 0)
return null;
return comments;
}
Here returning list is what I got from my presenter layer but when I receive that in my js method, its either null or previous value.
Here is my jQuery method..
function LoadComments(SysID, ObjID) {
if (parseInt(SysID) == 0 || parseInt(ObjID) == 0)
return;
var args = 'objID:' + ObjID + ',sysID:' + SysID;
$.ajax({
type: "POST",
url: "/dashboard/default.aspx/LoadComments",
cache: false,
data: '{' + args + '}',
contentType: "application/json",
dataType: "json",
success: function(result) {
if (result.d != null) {
comments = new Array();
$.each(result.d, function(key, val) {
data = new Object();
data.CommentID = val.CommentID;
data.Body = val.Body;
codate = new Date(parseInt(val.CreateDate.replace("/Date(", "").replace(")/", ""), 10));
var fdate = dateFormat(codate, "isoUtcDateTime");
ldate = $.timeago(fdate);
data.CreateDate = ldate;
data.CommentByAccountID = val.CommentByAccountID;
comments.push(data);
});
var boxid = "#commentBox_" + ObjID;
$(boxid).setTemplateURL("../Templates/comments.htm");
$(boxid).processTemplate(comments);
}
}
});
}
Please help me..
I found the solution... :)
First thing we could do is make our request async: false (BUT it'll impact our performance).. Instead, Im sending an ID (in my case SysID) and also bind it with my DIV id like the code below..
<div id ="comment_<%= SysID %>"></div>
In my jQuery function I use
var ID = "#comment_" + val.SysteID;
$(ID).setTemplateURL("../Templates/comments.htm");
$(ID).processTemplate(comments);
Hope it helps you guys too ... :)

Categories

Resources