I am using gldatepicker.I want to load some settings from database by ajax for gldatepicker such as day of week,special date etc.Now i have following js code for this:
$(document).ready(function () {
loadAllSettings();
});
var loadAllSettings = function () {
startDate = '';
endDate = '';
selectDay = '';
offdays = '';
$.ajax({
url: "bs_client_function.php",
type: "post",
dataType: "json",
data: {
action: 'getDateRange'
},
success: function (html) {
// alert(html.start);
startDate = Date.parse(html.start);
endDate = Date.parse(html.end);
}
});
$.ajax({
url: "bs_client_function.php",
type: "post",
dataType: "json",
data: {
action: 'getOffdays'
},
success: function (html) {
i = 0;
offdays = '[';
while (i < html.length) {
offdays = offdays + {
date: new Date(html[i]),
repeatYear: false,
cssClass: 'noday'
};
i = i + 1;
}
offdays = offdays + ']';
}
});
$.ajax({
url: "bs_client_function.php",
type: "post",
data: {
action: 'getDays'
},
success: function (html) {
var data = $.parseJSON(html);
// alert("[" + data + "]");
selectDay = '[' + data + ']';
// alert(selectDay);
showCalender(startDate, endDate, selectDay, offdays);
}
});
alert(selectDay);
console.log('selectDay' + selectDay);
};
I have checked all data is correctlly formated as gldatepicker recommanded.In my show calender
function:
var showCalender = function (startDate, endDate, selectDay, offdays) {
var dd = $('#mydate').glDatePicker({
showAlways: true,
allowMonthSelect: true,
allowYearSelect: false,
prevArrow: '\u25c4',
nextArrow: '\u25ba',
cssName: 'darkneon',
selectableDOW: selectDay,
dowOffset: 0,
selectedDate: new Date(),
selectableDateRange: [{
from: new Date(startDate),
to: new Date(endDate)
}, ],
specialDates: offdays
});
};
Now only stardate and enddate rightly working.selectDay,offdays are not working. i print selectDay in the console i got this: [1,2,3] but it not woking.What i am missing or what should be right way to do it.
Thanks in advance...
The problem is how you are getting your data for fill the glDatePicker.
You have 3 ajax calls, these calls are by default asynchronous, you execute your showCalender function in the last success function, but you have no sureness that the preceding calls are completed.
You can make your ajax calls synchronous by setting the async parameter to false see the jQuery docs:
async (default: true) Type: Boolean By default, all requests are sent
asynchronously (i.e. this is set to true by default). If you need
synchronous requests, set this option to false. Cross-domain requests
and dataType: "jsonp" requests do not support synchronous operation.
Note that synchronous requests may temporarily lock the browser,
disabling any actions while the request is active. As of jQuery 1.8,
the use of async: false with jqXHR ($.Deferred) is deprecated; you
must use the success/error/complete callback options instead of the
corresponding methods of the jqXHR object such as jqXHR.done() or the
deprecated jqXHR.success().
or you can chain them in every success callbacks, but your code will be difficult to mantain or you can use this plugin to manager multiple ajax calls http://docs.jquery.com/AjaxQueue
It works well with local data, see: http://jsfiddle.net/IrvinDominin/V59E7/
Pay attention only at the object that specialDates option needs:
specialDates: [{
date: new Date(0, 8, 5),
data: {
message: 'Happy Birthday!'
},
repeatYear: true,
cssClass: 'special-bday'
}, {
date: new Date(2013, 0, 8),
data: {
message: 'Meeting every day 8 of the month'
},
repeatMonth: true
}]
Related
I'm developing a drill down chart using Canvasjs and MVC5. I have a Controller called JsonController that contains several Tasks that return Json. They're all quite similar, but accept more arguments as the layers increase. Layer 0 is the default layer.
[HttpPost]
public async Task<IActionResult> GetLayer0(string datePassedIn)
{
string orgCode = User.Identity.GetOrgCode();
DateTime? processDate;
DateTime defaultDate = DateTime.Today.AddDays(-1); //default yesterday
try
{
processDate = DateTime.ParseExact(datePassedIn, inputDateFormat, cultureProvider);
}
catch (FormatException ex)
{
_logger.LogError(ex, "Error formatting date {datePassedIn} did not match {inputDateFormat}. using default date {defaultDate}", null);
processDate = defaultDate;
}
List<DataPoint> dataPoints = new List<DataPoint>();
IEnumerable<EventTypeLayer1> results = await _context.EventTypeLayer1Results
.FromSql($"usp_dd_EventType_0 #p0, #p1", orgCode, processDate)
.ToListAsync();
foreach (EventTypeLayer1 result in results)
{
dataPoints.Add(new DataPoint(result.Value, result.Title, result.Colour));
}
return Json(dataPoints);
}
In the javascript, the ajax calls are managed with an array
var ajaxOptions = [
{
url: "~/Views/Json/GetLayer0",
data: {
layer: 0,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode)
},
callback : handleLayer0
},
{
url: "~/Views/Json/GetLayer1",
data: {
layer: 1,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode),
eventType: encodeURIComponent(param.eventType)
},
callback : handleLayer1
},
{
url: "~/Views/Json/GetLayer2",
data: {
layer: 2,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode),
eventType: encodeURIComponent(param.eventType),
driverId: encodeURIComponent(param.driverId)
},
callback : handleLayer2
}
];
function doAjax( layerIndex) {
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: ajaxOptions[layerIndex].url,
data: ajaxOptions[layerIndex].data,
success: function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxOptions[layerIndex].callback(serverResponse);
},
complete : function () {
//note that the "success" callback will fire
//before the "complete" callback
console.log("Ajax call complete");
}
});
}
When the ajax fires, I'm getting Errors
https://localhost:44388/~/Views/Json/GetLayer0 error 404
https://localhost:44388/Json/GetLayer0 error 405
#Url.Action("GetLayer0", "JsonController") renders blank
I'm a bit confused. What should I do?
Edit: Here's the actual AJAX call
function doAjax( layerIndex) {
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: ajaxOptions[layerIndex].url,
data: ajaxOptions[layerIndex].data,
success: function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxOptions[layerIndex].callback(serverResponse);
},
complete : function () {
//note that the "success" callback will fire
//before the "complete" callback
console.log("Ajax call complete");
}
});
}
You are callig view urls instead of controller functions
It should be like
{
url: "/youcontrollername/GetLayer0",
data: {
layer: 0,
processDate: encodeURIComponent(formatDateInput(param.processDate)),
orgCode: encodeURIComponent(param.orgCode)
},
callback : handleLayer0
},
First or all.. i have browsed through tons of material and examples on this, but i cannot figure it out eitherhow..
Scenario :
Running on ASP.NET using Web Api 2...
API is called to fetch events, objects seems legit :
Issue seems to be that callback is never true..
Code :
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
events: function (start, end, callback) {
$.ajax({
type: "GET", //WebMethods will not allow GET
url: "api/Calendar/GetCalendarEvents/" + getQueryVariable("teamid"),
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = doc;
$(obj).each(function () {
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
if (callback) callback(events);
}
});
}
});
According to the official doc https://fullcalendar.io/docs/event_data/events_function/, function for programmatically generating Event Objects
function( start, end, timezone, callback ) { }
You should replace your events function with this:
events: function (start, end, timezone, callback) {
$.ajax({
type: "GET", //WebMethods will not allow GET
url: "api/Calendar/GetCalendarEvents/" + getQueryVariable("teamid"),
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = doc;
$(obj).each(function () {
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
if (callback) callback(events);
}
});
}
Because when you are calling with three parameters, fourth param callback is empty, that's the reason of not getting events.
I'm trying to create a web-page in EXTJs that has two major components:
A Form (Ext.form.Panel)
A Panel (Ext.tree.Panel)
The form is supposed to get some values, which should populate tree in second panel. In the button handler of the first panel I have access to the updated JSON object, but I cannot figure out a way to refresh the TreeStore that will update the display in tree.Panel.
This is what I have so far :
Ext.define('TreeServiceData',{
config:{
data : ''
},print : function() {
console.log("Printing data: ")
console.log(this.data.children[0])
}
});
var dataObject = Ext.create('TreeServiceData');
dataObject.setData({'expanded':false,'children':[{'text':'Master','expanded':true,'leaf':false,'children':[{'text':'Child 1','expanded':true,'leaf':false,'children':[{'text':'Child 2','expanded':true,'leaf':false,'children':[{'text':'Child 3','expanded':false,'leaf':false}]}]}]}]})
Ext.define('TreeStoreData',{
extend: 'Ext.data.TreeStore',
model: 'TaskModel',
autoLoad: true,
autoSync: true,
proxy: {
type:'memory',
reader: {
type:'json'
}
},
root:dataObject.getData()
});
var treeStore = Ext.create('TreeStoreData');
Now I'm trying to update and display the value of this treestore on a button call which looks like this :
buttons:[
{
text:'Get CCP/Product',
handler:function (btn, evt) {
dataObject.print();
treeStore.removeAll();
dataObject.setData({'expanded':false,'children':[{'text':'Master11','expanded':true,'leaf':false,'children':[{'text':'Child 12','expanded':true,'leaf':false,'children':[{'text':'Child 23','expanded':true,'leaf':false,'children':[{'text':'Child 34','expanded':false,'leaf':false}]}]}]}]})
dataObject.print();
}
}
]
But on this button handler I'm always getting a "Uncaught TypeError: Cannot call method 'indexOf' of undefined " on treeStore.removeAll() method, where treestore is clearly defined in this context.
Question 1) What is the correct way to refresh a TreeStore ?
Answer 1)
Instead of:
treeStore.removeAll();
dataObject.setData( ... );
You should do:
dataObject.setData( ... ); // This won't affect the store
treeStore.setRootNode(dataObject.getData()); // Actually update the store
Note that changing dataObject's data won't affect the store automatically like you seem to think...
this code works for me (ExtJS 4.2.1)
Total tree panel nodes refresh example:
var responseDictObjects = $.ajax({
data: { Id: this.idDictionary },
dataType: "json",
type: "POST",
cache: false,
url: 'http://' + config.domain + '/' + 'api/Dictionaries/GetDictTreeData',
async: false
}).responseText;
responseDictObjects = jQuery.parseJSON(responseDictObjects);
while (this.storeDict.getRootNode().firstChild) {
this.storeDict.getRootNode().removeChild(this.storeDict.getRootNode().firstChild);
}
this.storeDict.getRootNode().appendChild(responseDictObjects.Data);
Replace this.storeDict with your store reference.
In my case:
JSON.stringify(responseDictObjects.Data)
returns
"[{"id":8,"text":"kkk","leaf":false,"expanded":true,"children":null},{"id":17,"text":"ttttt","leaf":false,"expanded":true,"children":null},{"id":22,"text":"gggg","leaf":false,"expanded":true,"children":null},{"id":23,"text":"qqq","leaf":false,"expanded":true,"children":null},{"id":24,"text":"fff","leaf":false,"expanded":true,"children":null},{"id":27,"text":"fff","leaf":false,"expanded":true,"children":null},{"id":28,"text":"ggggggggggggggggggg","leaf":false,"expanded":true,"children":null},{"id":31,"text":"ttttttttttt666666666","leaf":false,"expanded":true,"children":null},{"id":32,"text":"ffffffffffffffffffff","leaf":false,"expanded":true,"children":null},{"id":33,"text":"kkkkkkkkkkkkk","leaf":false,"expanded":true,"children":null},{"id":35,"text":"7777777777","leaf":false,"expanded":true,"children":null},{"id":36,"text":"999999999999","leaf":false,"expanded":true,"children":null},{"id":37,"text":"iii","leaf":false,"expanded":true,"children":null}]"
I found another bug with TreePanel, previosly removed nodes appears after executing appendChild. So i started to use jquery tree plugin (dynatree). All you need is to create empty panel. And after render a panel, embed tree, in my case:
Create empty panel:
that.treePanel = Ext.create('Ext.panel.Panel', {
title: 'Records',
width: 350,
height: 400
});
After rendering panel you can refresh nodes whenever you want:
var that = this;
var responseDictObjects = $.ajax({
data: { Id: this.idDictionary },
dataType: "json",
type: "POST",
cache: false,
url: 'http://' + config.domain + '/' + 'api/Dictionaries/GetDictTreeData',
async: false
}).responseText;
responseDictObjects = jQuery.parseJSON(responseDictObjects);
var el = this.treePanel.getId();
if (this.treeDict == null) {
this.treeDict = $('#' + el).dynatree({
onActivate: function (node) {
that.treeDict.lastSelectedId = node.data.index;
},
children: []
});
}
this.treeDict.dynatree("getRoot").removeChildren(true);
this.treeDict.dynatree("getRoot").addChild(responseDictObjects.Data);
The idea
is i have calendar control from where i can select different dates. Based upon the dates selected i make a ajax call to WCF service (GetDealData()) to fetch some sets of data.
Could you anyone please see whats wrong here? For two days i am going a bit crazy trying to figure out why does my GetRemoteData() method passes the same date (which is 25-10-2012) everytime i execute the OnDateChange Method even if i select different dates on my calendar control. Is it something to do with json data not being assigned properly?
$('#calendarContainer').kendoCalendar({
format: "dd/MM/yyyy",
culture: "en-GB",
change: onDateChange
});
function onDateChange() {
var date = kendo.toString(this.value(), 'dd/MM/yyyy');
var bob = GetRemoteData(date);
$("#grid").data("kendoGrid").dataSource.data(bob);
$("#grid").data("kendoGrid").dataSource.read();
}
function GetRemoteData(date) {
var chosenDate;
if (typeof date=="undefined")
{
alert("it is null " + date);
chosenDate = "25-10-2012";
}
else {
alert("it is not null " + date);
chosenDate = date;
}
source = new kendo.data.DataSource({
// autoSync:true,
transport: {
read: {
type: "GET",
url: "http://localhost:35798/RestServiceImpl.svc/GetDealData",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
cache: false,
data: {
startDate:chosenDate
}
}
},
schema: {
model: {
fields: {
DealNumber: { type: "string" },
DealIssuer: { type: "string" },
Ticker: { type: "string" },
DealType: { type: "string" },
DealValue: { type: "number" },
DealStatus: { type: "string" },
DealPricingCompletionDate: { type: "date" }
}
}
},
pageSize: 16
});
return source;
}
WCF Methods
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetDealData?startDate={startDate}")]
List<DealData> GetDealData(string startDate);
public List<DealData> GetDealData(string startDate)
{
CultureInfo culture = new CultureInfo("en-GB");
List<DealData> model = Service.GetDealData(Convert.ToDateTime(startDate,culture));
return model;
}
From your code, it seems that this issue does not related to wcf - its just a JavaScript issue.
It seems, that your date is always undefined.
I'd try to find out what is the value of this.value(), and after this - kendo.toString(this.value(), 'dd/MM/yyyy') value.
For me its sound like some format issue may be.
You can use browser's console to debug JavaScript
I'm want to add a parameter named foo to the request that fullcalendar submits when retrieving event data. According to the docs this can be achieved using:
var getFoo() = function() {
// implementation omitted
};
$('#calendar').fullCalendar({
loading: function(isLoading) {
// CAN I SOMEHOW UPDATE foo FROM HERE?
},
events: {
url: '/myfeed.php',
type: 'POST',
data: {
foo: getFoo()
}
}
});
I want the value of the foo parameter to be calculated each time the calendar event data is requested, but it seems that fullcalendar only calls getFoo() the first time it loads, then re-uses that value for each subsequent request.
I've tried using this the loading event that is triggered immediately before the data is loaded, but I can't figure out how to update the foo paramter from within this function.
Update
I followed the advice below and got it working with this:
$('#calendar').fullCalendar({
events: function(start, end, callback) {
$.ajax({
url: 'getCalendarEvents',
dataType: 'json',
data: {
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
foo: getFoo()
},
success: function(doc) {
var events = eval(doc);
callback(events);
}
});
},
});
Maybe you could use the events as function to create your own ajax request.
var getFoo() = function() {
// implementation omitted
};
$('#calendar').fullCalendar({
events: function(start, end, callback) {
var myFoo = getFoo();
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
foo: myFoo
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
Try setting lazyFetching to false. I'm guessing you're having this problem because fullCalendar tries to save you from unnecessary ajax requests.
Fullcalendar doc on lazyFetching