Is there a way to disable cache on FullCalendar? - asp.net

I'm using FullCalendar on asp.net application. I noticed that when FullCalendar receives data from SQL Server via Web-Method > JSON, it creates a cache file (EventList.json) inside browser history/temporary folder.
I have cache:false on every method but I don't know how to apply the same thing on events: calendar.asmx/EventList .
Please refer to my other post that shows how I receive my data via web-method.
So my questions are:
Is there a way to disable cache on events?
How can I use ajax like other methods to get data, because with this method I can disable cache
function runCalendar() {
var $modal = $('#event-modal');
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* Initialize the calendar */
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var form = '';
var today = new Date($.now());
var calendar = $('#calendar').fullCalendar({
slotDuration: '00:15:00',
/* If we want to split day time each 15minutes */
minTime: '08:00:00',
maxTime: '20:00:00',
timeFormat: 'HH(:mm)',
defaultView: 'agendaWeek',
events: "calendar.asmx/EventList",
lazyFetching: false,
allDaySlot: false,
firstDay: 1,
//weekends: false,
handleWindowResize: true,
//columnFormat:'ddd / DD',
selectHelper: true,
height: $(window).height() - 200,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
eventLimit: true, // allow "more" link when too many events
drop: function(date) {
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
var $categoryClass = $(this).attr('data-class');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
if ($categoryClass) copiedEventObject['className'] = [$categoryClass];
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
selectable: true,
eventClick: function(calEvent, jsEvent, view) {
var form = $("<form></form>");
form.append("<label>Change event name</label>");
form.append("<div class='input-group'><input class='form-control' type=text value='" + calEvent.title + "' /><span class='input-group-btn'><button type='submit' class='btn btn-success'><i class='fa fa-check'></i> Save</button></span></div>");
$modal.modal({
backdrop: 'static'
});
$modal.find('.delete-event').show().end().find('.save-event').hide().end().find('.modal-body').empty().prepend(form).end().find('.delete-event').unbind('click').click(function() {
calendar.fullCalendar('removeEvents', function(ev) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/DeleteCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "'}",
});
return (ev._id == calEvent._id);
});
$modal.modal('hide');
});
$modal.find('form').on('submit', function() {
calEvent.title = form.find("input[type=text]").val();
calendar.fullCalendar('updateEvent', calEvent);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/UpdateCalendarEvent",
dataType: "json",
data: "{'id':'" + calEvent._id + "','title':'" + calEvent.title + "'}",
});
$modal.modal('hide');
return false;
});
},
eventDrop: function(event, ui, jsEvent) {
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/MoveEvents",
dataType: "json",
data: "{'id':'" + event._id + "','start':'" + moment(event.start).format("DD MMMM YYYY HH:mm:ss") + "','end':'" + moment(event.end).format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
eventResize: function(event, allDay) {
var allDay = !event.start.hasTime() && !event.end.hasTime();
$.ajax({
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/ResizeEvents",
dataType: "json",
data: "{'id':'" + event._id + "','end':'" + event.end.format("DD MMMM YYYY HH:mm:ss") + "','allDay':'" + event.allDay + "'}",
});
},
select: function(start, end, allDay) {
$modal.modal({
backdrop: 'static'
});
form = $("<form></form>");
form.append("<div class='row'></div>");
form.find(".row")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Event Name</label><input class='form-control' placeholder='Insert Event Name' type='text' name='title'/></div></div>")
.append("<div class='col-md-6'><div class='form-group'><label class='control-label'>Category</label><select class='form-control' name='category'></select></div></div>")
.find("select[name='category']")
.append("<option value='busy'>Busy</option>")
.append("<option value='e1'>E1</option>")
.append("<option value='e2'>E2</option>")
.append("<option value='bg-blue'>Lunch</option>")
.append("<option value='bg-yellow'>Children</option></div></div>");
inputSelect();
$modal.find('.delete-event').hide().end().find('.save-event').show().end().find('.modal-body').empty().prepend(form).end().find('.save-event').unbind('click').click(function() {
form.submit();
});
$modal.find('form').on('submit', function() {
title = form.find("input[name='title']").val();
beginning = form.find("input[name='beginning']").val();
ending = form.find("input[name='ending']").val();
$categoryClass = form.find("select[name='category'] option:checked").val();
var allDay = !start.hasTime() && !end.hasTime();
if (title !== null && title.length != 0) {
//calendar.fullCalendar('renderEvent', {
// title: title,
// start:start,
// end: end,
// allDay: false,
// className: $categoryClass
//}, true);
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "calendar.aspx/CreateCalendarEvent",
dataType: "json",
data: "{'title':'" + title + "','start':'" + start.format("DD MMMM YYYY HH:mm:ss") + "','end':'" + end.format("DD MMMM YYYY HH:mm:ss") + "','category':'" + $categoryClass + "','allDay':'" + allDay + "'}",
success: function(data) {
var obj = data.d;
if (obj == 'true') {
//$('#txtFirstName').val('');
//$('#txtLastName').val('');
//$('#txtCity').val('');
//$('#txtEmailID').val('');
//$('#lblmsg').html('Data Inserted Successfully');
}
},
error: function(result) {
alert(result);
}
});
calendar.fullCalendar('refetchEvents')
$modal.modal('hide');
} else {
alert('You have to give a title to your event');
}
return false;
});
calendar.fullCalendar('unselect');
}
});
/* Creation of new category */
$('.save-category').on('click', function() {
formCategory = $('#add-category form');
var categoryName = formCategory.find("input[name='category-name']").val();
var categoryColor = formCategory.find("select[name='category-color']").val();
if (categoryName !== null && categoryName.length != 0) {
$('#external-events').append('<div class="external-event bg-' + categoryColor + '" data-class="bg-' + categoryColor + '" style="position: relative;"><i class="fa fa-move"></i>' + categoryName + '</div>')
runCalendar();
}
});
}
$(function() {
runCalendar();
});

Instead of:
events: "calendar.asmx/EventList",
following method can disable the cache
eventSources: [{
url: 'calendar.asmx/EventList',
type: 'POST',
cache: false
}],

According to FullCalendar documentation your call already prevents the browser from caching, and the fact that FullCalendar is a jQuery plugin means that under the hood it probably uses jQuery's $.ajax() method to retrieve the data.

In my case I had to turn off both lazyFetching and events cache:
eventSources: [
{
url: ...,
cache: false,
}
],
lazyFetching: false

Related

Get Kendo Grid checkbox status on custom command

I have a kendo grid with 4 checkbox columns with checked and unchecked status.
Now I want to updated tabel based on checkbox checked status on custom command button click.
Here is my kendo grid binding code
$(document).ready((function () {
$.ajax({
type: "POST",
url: "member-security-list.aspx/getStatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#grid").kendoGrid({
dataSource: {data: response.d,pageSize: 20},
sortable: {mode: "single",allowUnsort: false},
pageable: {buttonCount: 5},
scrollable: false,
columns: [
{ field: "login", title: "Login Id" },
{ field: "name", title: "Member Name" },
{ field: "mobile", title: "Mobile No." },
{ field: "Alert Status", template: "<input type='checkbox' value='oncredit' class='oncredit' #if(oncredit === '1'){#= checked='checked' #}else{}#= />On Credit <input type='checkbox' value='ondebit' class='ondebit' #if(ondebit === '1'){#= checked='checked' #}else{}#= />On Debit <input type='checkbox' value='onlogin' class='onlogin' #if(onlogin === '1'){#= checked='checked' #}else{}#= />On Login <input type='checkbox' value='isblock' class='isblock' #if(isblock === '1'){#= checked='checked' #}else{}#= />Block SMS Recharge" },
{ command: { text: "Set", click: showDetails }, title: "Set" }
]
});
},
failure: function (response) {
alert(response.d);
}
});
}));
and here is my command button click code
function showDetails(e) {
e.preventDefault();
var d = this.dataItem($(e.currentTarget).closest("tr"));
//I want to access checkbox here and find its checked status for pass parameter.
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","status":"' + d.status + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
//some other
},
failure: function (response) { }
});
}
Now I have solved my problem. Here is my working code
function showDetails(e) {
e.preventDefault();
var credit, debit, login, block;
var d = this.dataItem($(e.currentTarget).closest("tr"));
var tr = $(e.target).closest("tr");
if (tr.find('.oncredit').is(':checked'))
credit = '1';
else
credit = '0';
if (tr.find('.ondebit').is(':checked'))
debit = '1'
else
debit = '0';
if (tr.find('.onlogin').is(':checked'))
login = '1';
else
login = '0';
if (tr.find('.isblock').is(':checked'))
block = '1'
else
block = '0';
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","oncredit":"' + credit + '","ondebit":"' + debit + '","onlogin":"' + login + '","isblock":"' + block + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
alert('Updated');
},
failure: function (response) { }
});
}

Full calendar event rendering happens only for particular week

I am using fullcalendar plugin to display data for one week. The problem is event is rendering only for the week which i select first. Later when i change week events are getting created but are not rendering. When i change again to week I selected first, event creation and rendering both happens. I am using $('#calendar').fullCalendar('gotoDate', WeekStartDate) to go to desired week.
$.ajax({
type: "POST",
contentType: "application/json",
data: '{}',
url: 'DataService.svc/CMStrandSelection',
dataType: "json",
async: false,
success: function (data) {
$('#calendar').fullCalendar({
header: {
left: '',
center: '',
right: '',
height: 300
},
defaultView: 'basicWeek',
editable: true,
columnFormat: 'DD dddd',
events:
$.map(data.d, function (item, i) {
debugger;
var event = new Object();
event.id = item.eventId;
event.start = item.Start;
event.end = item.Endd;
event.title = item.Title
event.color = 'White';
event.allDay = true; //
return event;
}),
eventRender: function (event, element) {
//some code
});
}
});
$('#calendar').fullCalendar('option', 'height', 400);
}
});

how to call popup window while ajax callback post method waiting to response in asp.net

1) my call back function
function fetch_servicedata1() {
var filename = document.getElementById("ctl00_ContentMain_hdnfile").value;
companyID = document.getElementById('ctl00_ContentMain_hdnCompanyID').value;
var service_Res = "";
$.ajax({
type: "POST",
url: "UtilityService.asmx/New_FatchCacheXMLString",
data: "filename=" + filename + "&CompanyID=" + companyID+"&Rq_CID=1",
dataType: "xml",
// cache: false,
async: false,
success: function (xml) {
// alert('first relsut');
if (xml.documentElement.text) {
fnFetchResult_New(xml.documentElement.text);
}
else {
fnFetchResult_New(xml.documentElement.textContent);
}
if(TotalResultCount>0)
document.getElementById("divProgressBar").style.display = '';
secondPagingFlag = true;
console.log('before func 2');
// setTimeout(fetch_servicedata2(), 1);
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
// alert(thrownError);
// $('#waitScreen').css('display', 'none'); $('#waitBox').css('display', 'none');
}
});
}
2) my event
$(".external-link").live("click", function (e) {
$.ajax({
type: "GET",
async: true,
url: "",
success: function () {
window.open("HtlIntermediate.aspx");
}
})
});
i need to event call without wait for call back success
i have called call back function and it will take around 1 minute to response and in the meantime need to click on the button and open popup window which show data from database using asp.net
you can use beforeSend and complete parameter in jquery ajax
http://api.jquery.com/jquery.ajax/
$.ajax({
type: "GET",
async: true,
beforeSend:function(){window.open("HtlIntermediate.aspx"); },
complete:function(){//close window
},
url: "",
success: function () {
// process other stuff
}
})

jqgrid edit call ajax every time

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si รจ verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid
You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

Jquery Cascading Drop Down how to trigger the change event for all the dropdowns in the chain Sequencially

I have the following jQuery code in my application that drives four cascading dropdowns. I have seen numerous examples online that force the user to select a value by adding a '--Select a Value---' option. However, what I am trying to do is, for the dropdowns, update automatically in the order if one of them changes.
update 2,3,4 if 1 changes and 3,4 if 2 changes, etc.
Dropdown1 Center Dropdown2 Geo Dropdown3 Sup Dropdown4 Emp
This is the jQuery code I have:
$(function() {
$('#divParentaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#divGenericaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#<% =ddCenter.ClientID %>').change(getGeo());
$('#<% =ddGeo.ClientID %>').change(getSup());
$('#<% =ddSup.ClientID %>').change(getEmp());
// Statements i assume should call the function when the event triggers
})
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
}
})
}
function getSup() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetSupList",
data: "{center:'" + center + "',geo:'" + geo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var sups = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddSup.ClientID %>').removeOption(/./);
for (var i = 0; i < sups.length; i++) {
var val = sups[i].SOPId;
var text = sups[i].Name;
$('#<% =ddSup.ClientID %>').addOption(val, text);
}
}
})
}
function getEmp() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
var sup = $('#<% =ddSup.ClientID %>').val();
$.ajax({
type: "POST",
url: "ObservationsReport.aspx/GetEmpList",
data: "{center:'" + center + "',geo:'" + geo + "',sup:'" + sup + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var emps = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddEmp.ClientID %>').removeOption(/./);
for (var i = 0; i < emps.length; i++) {
var val = emps[i].Sop_Id;
var text = emps[i].Name;
$('#<% =ddEmp.ClientID %>').addOption(val, text);
}
}
})
}
What am I doing wrong? I have recently started programming in jQuery; still not completely familiar with how it handles the events and when. Please, any help will be appreciated.
I think your issue is that you're expecting the population of a box from the ajax call to trigger that select's onchange. This is not the case. Changes through javascript do not fire onchange. You will need to fire the onchange yourself.
For example, try changing getGeo to this:
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
// *** CALL getSup directly ***
getSup() ;
}
})
}
The key here is the explicit call to getSup as it will not be triggered onchange.

Resources