press confirm button before save - javascript

I'm having a problem with the way I save information in ajax with alert, I made it using confirm in JQuery but the button text can't be changed I so decided to make my own dialog box so I can modify the buttons, but the problem is the data saves before I click the save button.
function saveEdit(e) {
var result = '';
var item = $('input[name=username]').val();
$.ajax({
url: root + 'ccards/getAllDetails',
data: {
item: item
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hour = dateObj.getUTCHours()
var minute = dateObj.getUTCMinutes();
var second = dateObj.getUTCSeconds();
var datetoday = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
var selected_date = Date.parse(data.modified);
var today = Date.parse(datetoday);
var d = new Date(data.modified);
var h = d.getHours();
var m = d.getMinutes();
var username = data.username.toUpperCase();
var coreuser = data.core_user.username.toUpperCase();
var hr = '';
var time = '';
if (h <= '12') {
hr = h;
time = hr + ":" + m + " AM";
} else {
hr = h - 12;
time = hr + ":" + m + " PM";
}
if (Math.abs(today - selected_date) <= 60 * 60 * 24 * 1000) {
$('#confirmSave').show().dialog({
height: 200,
width: 500,
zIndex: 10,
modal: true,
resizable: false
});
$('#time').html(time);
$('#coreuser').html(coreuser);
if ($('#confirmSave button[name=submit]').data('clicked')) {
result = true;
} else if ($('#confirmSave button[name=cancel]').data('clicked')) {
result = false;
}
}
}
});
return result;
}
$('.clientForm').submit(function(event) {
var form = this;
console.log(form);
if ($("input[name='action']", form).val() == 'save' || $("input[name='action']", form).val() == 'savenew' || $("input[name='action']", form).val() == 'login') {
if ((!validate_email(form)) || (!validate(form))) {
mode = 'edit';
setMode(mode);
return false;
}
}
var save = saveEdit();
if (save == true) {
var dt = $(this).serializeArray();
var action = root + $("input[name='module']", form).val() + $("input[name='method']", form).val();
$('.fields', this).slideUp('fast');
$('.response', this).html("<div class='load'>Processing, please wait...</div>");
$.ajax({
type: 'POST',
url: action,
data: dt,
dataType: 'json',
success: function(data) {
if (data) procJSON.init(data, form);
},
complete: function(data) {
},
error: function(data) {
onError(data);
}
});
}
return false;
});

I recently used the noty plugin, alongside jQuery's deferred to solve a similar problem.
First, a function to show the confirm dialog and return a promise-like object, which resolves to true if the Ok button is pressed, or false if the Cancel button is pressed.
function showConfirm(msg) {
var dfd = $.Deferred();
noty({
text: msg,
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme',
modal: true,
buttons:
[{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: $noty => {
$noty.close();
dfd.resolve(true);
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: $noty => {
$noty.close();
dfd.resolve(false);
}
}]
});
return dfd.promise();
}
Then you can do something like...
$('.clientForm').submit(function(event) {
showConfirm("Do you wish to save?").then(function(confirmed) {
if (!confirmed) {
return;
}
// make ajax request here
}
}

Related

Full calendar updateEvent. Cannot read property 'clone' of undefined

I'm using FullCalendar and trying to update an event with a modal. When I try to update the event, I'm getting the cannot read property 'clone' of undefined.
I'm using the clientEvents method, as stated in their documentation
event must be the original Event Object for an event, not merely a reconstructed object. The original Event Object can obtained by callbacks such as eventClick, or by the clientEvents method.
to get my original event, however, when I submit I still get this error.
Here's my code:
initializeFullCalendar: function () {
var loc = $('#locationCodes').val();
$('.autocomplete').keypress(function (key) {
if (key.charCode == 32 && $('.autocomplete').val().length >= 1) { return true };
// if (key.charCode == 92 || key.charCode == 47 || key.charCode < 65) return false;
});
$(document).tooltip({
track: true,
hide: { effect: "explode", duration: 300 }
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
selectable: true,
selectHelper: true,
dayclick: function(date){
},
select: function (date, start, end) {
if ($('#job').attr('class') === 'XXX') {
EMP.calendarPopup(date, start, end);
}
},
eventSources: [
{
url: '/Home/getAllEvents/',
data: { Locations: loc },
type: 'POST'
}
],
eventClick: function (event, element, date) {
EMP.editCalendarPopup(date, event);
},
height: 350,
defaultView: 'basicWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventRender: function (data, element) {
var start = moment(data.start._i).format('LT');
var end = moment(data.end._i).format('LT');
}
});
},
editCalendarPopup: function (date, event) {
$('.calendar-popup').addClass('active edit');
var event_date = event.start._i.split("T")[0];
var start = event.start._i.split("T")[1]
var end = event.end._i.split("T")[1];
start = EMP.convert12hr(start);
end = EMP.convert12hr(end);
var startTime = start.split(' ')[0];
var startMod = start.split(' ')[1];
var endTime = end.split(' ')[0];
var endMod = end.split(' ')[1];
$('#date').val(event_date);
$('#calendar-event').val(event.title);
$('#calendar-custodian').val(event.cust);
$('#calendar-start').val(startTime);
$('#startampm').val(startMod)
$('#calendar-end').val(endTime);
$('#endampm').val(endMod);
$('#hiddenEvent').val(event.title);
$('#hiddenCustodian').val(event.cust);
$('#hiddenStart').val(event.start._i);
$('#hiddenEnd').val(event.end._i);
$('#hiddenId').val(event._id);
},
editCalendarAjax: function() {
var event = $("#calendar").fullCalendar('clientEvents');
var hiddenId = $('#hiddenId').val();
event = $.grep(event, function(e){return e._id === hiddenId});
event = event[0];
var event_date = $('#date').val();
var title = $('#calendar-event').val();
var cust = $('#calendar-custodian').val();
var start = $('#calendar-start option:selected').val();
var end = $('#calendar-end option:selected').val();
var startampm = $("#startampm option:selected").val();
var endampm = $("#endampm option:selected").val();
start = start + " " + startampm;
end = end + " " + endampm;
start = EMP.convert24hr(start);
end = EMP.convert24hr(end);
var locCode = $('.location').attr('id');
var date_start = event_date + "T" + start;
var date_end = event_date + "T" + end;
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
var origEvent = $('#hiddenEvent').val();
var origCust = $('#hiddenCustodian').val();
var origStart = $('#hiddenStart').val();
var origEnd = $('#hiddenEnd').val();
item = {};
item["title"] = title;
item["cust"] = cust;
item["start"] = date_start;
item["end"] = date_end;
item["locCode"] = locCode;
item["origEvent"] = origEvent;
item["origCust"] = origCust;
item["origStart"] = origStart;
item["origEnd"] = origEnd;
$.ajax({
type: "POST",
url: "/Home/updateCalendar",
data: item,
success: function () {
console.log('success!');
},
error: function (xhr, ajaxOptions, thrownError) {
window.alert("Please click here to refresh your session");
console.log('error')
}
});
$('#calendar').fullCalendar('unselect');
EMP.togglePopups();
},
The issue was I was using an old version of FullCalendar. After updating I stopped getting the error.
One more thing I had to change was this:
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
to this:
if (title) {
event.title = title;
event.start = date_start;
event.cust = cust;
event.end = date_end;
$('#calendar').fullCalendar('updateEvent', event); // stick? = true
}
because I was overwriting my event. Everything works now.

eventRender not rendering nor displaying events on fullcalendar

Good day, i'm using fullcalendar plugin to show events on my calendar. right now i'm having a problem on displaying the events in my calendar. i am using json result to get the data that will show on my calendar..
here's my code
Controller:
[DontWrapResult]
public JsonResult GetCalendarEvents(string start, string end)
{
var fromDate = Convert.ToDateTime(start);
var toDate = Convert.ToDateTime(end);
var result = _utils.GetEventsCalendar("ALL", fromDate, toDate);
var eventList = from item in result
select new
{
id = item.CalendarId.ToString(),
title = item.Title,
description = item.Description,
start = item.FromDate.ToLocalTime().ToString("s"),
end = item.EndDate.HasValue ? item.EndDate.Value.ToLocalTime().ToString("s") : item.FromDate.ToLocalTime().ToString("s"),
NoofGuests = item.NoofGuests,
allDay = item.AllDay,
type = item.CalType,
requestedBy = item.RequestedBy,
driverName = item.DriverName,
providerName = item.ProviderName,
phoneNo = item.PhoneNo,
controlNumber = item.ControlNumber,
status =item.StatusId
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
then in my javascript:
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
droppable: false, // this allows things to be dropped onto the calendar
events: '#Url.Action("GetCalendarEvents/")',
eventRender: function (event, element) {
element.attr('href', 'javascript:void(0);');
if (event.start <date && event.end <date) {
element.css('background-color', '#ed5565');
element.css('border', '1px solid #ed5565');
} else if (event.start <=date && event.end >= date) {
element.css('background-color', '#f8ac59');
element.css('border', '1px solid #f8ac59');
}
if (event.status == 1) {
element.css('background-color', '#0000FF');
element.css('border', '1px solid #0000FF');
} else if (event.status == 4)
{
element.css('background-color', '#00CC33');
element.css('border', '1px solid #00CC33');
}
element.click(function () {
if (event.type == 'Event') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Events")?id=' + event.id;
}
else if (event.type == 'ApproveBook') {
$('#forBook').show();
$('#permitdetails').hide();
$('#delPer').show();
$("#NoofGuests").html(event.NoofGuests);
}
else {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
var url = '#Url.Action("Edit", "Announcements")?id=' + event.id;
}
if (event.type == 'DeliveryPermit') {
$('#delPer').hide();
$('#permitdetails').show();
$("#controlNo").html(event.controlNumber);
$("#requestby").html(event.requestedBy);
$("#deliverydate").html(moment(event.start).format('MMM Do'));
$("#contractor").html(event.providerName);
$("#contact").html(event.phoneNo);
$("#drivername").html(event.driverName);
if (event.status == 1) { $("#status").html("Arrived"); }
else if (event.status == 4) { $("#status").html("Completed"); }
else { $("#status").html("Submitted"); }
//getDetails(event.id);
var urls = '#Url.Action("Calendarpermit", "AdminHome")?id=' + event.id + '&strHide=' + "strHide";
var url = '#Url.Action("Edit", "DeliveryPermits",new { area = "Permit" })/' + event.id
$.ajax({
url: urls,
cache: false,
data: {id : event.id},
contentType: 'application/html; charset=utf-8',
type: "POST",
dataType: "html",
success: function (data){
$('#permitItem').html(data);
}
});
}
if (event.type == 'Announcement') {
$('#forBook').hide();
$('#permitdetails').hide();
$('#delPer').show();
$("#startTime").html(moment(event.start).format('MMM Do '));
$("#endTime").html(moment(event.start).format('MMM Do'));
} else {
$("#startTime").html(moment(event.start).format('MMM Do h:mm A'));
$("#endTime").html(moment(event.end).format('MMM Do h:mm A'));
}
$("#eventInfo").html(event.description);
$("#eventLink").attr('href', url);
$("#eventContent").dialog({
modal: true, title: event.title, width: 350
});
});
}
});
i tried to put an alert inside the eventRender but it didn't pass or show data in my calendar.. what i am doing wrong? thanks in advance

Tree_view undefined after read kendo tree

Here's my problem:
I load a first time my tree to display him.
I can change the value of the Session's files name "state" to enable or disable a node in my tree.
But after I change ne value in my database and return the JSON, I read again the tree to refresh my tree with the changes but it's failed and write in console :
" TypeError: Tree_view.getElementsByClassName(...)[0].children[(item.id_perso - 1)].children[1] is undefined".
That I don't understand is I pass my first time by these functions and it work well, but when I reload it failed apparently because the it undefined.
Thank's for any help.
$(document).ready(function() {
$('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node);
var treeview = $('#Tree_view').data('kendoTreeView');
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
if (item.level() == 0) {
setTimeout(function() { waitDisable(item, treeview); }, 1000);
}
}
function waitDisable(item, treeview) {
if (item.fields.type == "parcours")
{
var node = Tree_view.getElementsByClassName('k-group')[0].children[item.id_perso - 1].children[1].children;
for (i = 0; i < item.children._data.length; i ++)
{
if (item.children._data[i].state != null) {
node[i].children[0].children[1].className = "k-in k-state-disabled";
node[i].children[0].children[0].className = ".k-icon-remove";
}
else node[i].children[0].children[0].className = "k-icon k-plus";
addRow(node, item, i, treeview);
}
}
}
var cmp = 0;
var One_Time = false;
function addRow(node_Here, item, i, treeview) {
var actual_row = node_Here[i].children[0];
if (actual_row.childNodes.length < 3) {
var newSpan = document.createElement('button');
if (item.children._data[i]._childrenOptions.data.state != null) {
newSpan.appendChild(document.createTextNode("Re-Up"));
newSpan.className = "change_state btn btn-success btn-xs";
}
else {
newSpan.appendChild(document.createTextNode("Down"));
newSpan.className = "change_state btn btn-danger btn-xs";
}
actual_row.appendChild(newSpan);
}
cmp += 1;
if (cmp == item.children._data.length)
One_Time = true;
if (One_Time) {
addClickListner(item, i, treeview);
One_Time = false;
cmp = 0;
}
}
function addClickListner(item, i, treeview) {
$(".change_state").click(function (event) {
var name_Promo_Rm = event.target.parentNode.children[1].textContent;
var User_Select = event.view.Parcours.transport.read.data.user_id;
$.ajax({
url: '#Url.Action("ChangeStatutBase", "Users")',
type: 'GET',
dataType: 'json',
data: { Name_Promo: name_Promo_Rm, User_id: User_Select },
});
refreshTree(treeview);
})
}
// Refresh tree
function refreshTree(treeview) {
// Save open items
saveExpandedItems(treeview);
// Reload data source
treeview.dataSource.read();
// Load open items
console.log("OKKKKKKK");
setTimeout(loadExpandedItems(), 600);
}
I've resolved my problem, in the "setTimeout" in the bottom I've placed "()" in the first parameter and it doesn't put the pause and data don't have the time to be loaded.

undefined result conditions forecast

I edit some code jquery weather , and when I add some Response Fields not all Fields clear result I have undefined result conditions .
Example : Max. temp: 42C / 108F Min. temp: 27C / 80F wind : undefined
$(function() { var handlers = {
simplePrint : function (location){
var new_location_div = $('<div>');
new_location_div.addClass('location');
new_location_div.data('l',location.l);
new_location_div.data('city',location.name);
var location_p = $('<p>').text(location.name)
new_location_div.append(location_p);
$('#search_result').append(new_location_div);
},
displayPrint : function (location,day){
var display = $('<div>');
display.addClass('display_on')
location = $('<p>').text('Location: ' + location);
high_temp = $('<p>').text('Max. temp: ' + day.high.celsius + 'C / ' + day.high.fahrenheit + 'F');
min_temp = $('<p>').text('Min. temp: ' + day.low.celsius + 'C / ' + day.low.fahrenheit + 'F');
wind_dir = $('<p>').text(' ' + day.wind_dir +' ');
display.append(location,high_temp,min_temp,wind_dir);
// "Thunderstorm" "Chance of Rain" "Overcast" "Partly Cloudy" "Rain" "Clear"
$('#display_today').slideUp('slow');
var condition = ['clear', 'sunny'].indexOf(day.conditions.toLowerCase())
if (condition === -1 ) {
$('body').fadeTo('slow', 0, function()
{
$(this).css('background-image', 'url("http://harrymoroz.com/wp-content/uploads/2014/04/1_See_It.jpg")');
}).fadeTo('slow', 1);
$('h1').css({'color': 'white'});
$('.starter-template > p').css({'color': 'white'});
}else{
$('body').fadeTo('slow', 0, function()
{
$(this).css('background-image', 'url("https://melodywren.files.wordpress.com/2011/04/p1040585.jpg")');
}).fadeTo('slow', 1);
$('h1').css({'color': 'rgb(#333)'});
$('p').css({'color': 'rgb(#333)'});
};
setTimeout(function(){
$('.display_on').remove();
$('#display_today').append(display);
$('#display_today').slideDown('400');
}, '800'); } } $('#search_form_submit').on('click keypress', function(event) {
event.preventDefault();
var search_query = $('#search_field').val();
if (!search_query) {
$('.location').remove();
return;
};
$.ajax({
url: 'http://autocomplete.wunderground.com/aq?query=' + search_query ,
type: 'GET',
dataType: 'jsonp',
jsonp: 'cb',
})
.done(function(search_api_answer) {
$('.location').remove();
search_api_answer.RESULTS.filter(function(location){
return location.type === 'city'
}).forEach(handlers.simplePrint);
});
$('#search_form').trigger("reset");
});$('#search_result').on('click', '.location', function(event) {
event.preventDefault();
var selected_location = $(this)
var lCode = selected_location.data('l');
$.ajax({
url: 'http://api.wunderground.com/api/0ce1c4a981f7dd2a/conditions/forecast/q/'+ lCode + '.json',
type: 'GET',
dataType: 'json',
// jsonp: 'cb',
})
.done(function(api_city_forecast,conditions) {
todayForecast = api_city_forecast.forecast.simpleforecast.forecastday[0];
cityForecast = selected_location.data('city');
conditions = conditions.current_observation;
handlers.displayPrint(cityForecast,todayForecast,conditions);});});});
Looking at the result of:
http://api.wunderground.com/api/0ce1c4a981f7dd2a/conditions/forecast/q/kzn.json
it seems that some items, like the "day" variable, may not always be filled out how like you expect. Specifically, the "day" variable in that JSON response has no "high" or "low" attribute -- it simply has a valuel.
You might want to make your app cater for this condition, ie when weatherunderground doesn't know all values for a query, but provides a base value.

JavaScript function array return undefined

I am using AJAX to get the data and make them into an array like below:
function drawDate(username, date, device, token){
$.ajax({
type: 'GET',
url: dsu + "dataPoints/" + getDatapointId(username, date, device),
headers: {
"Authorization": "Bearer " + token
},
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
return location_events
}
},
error: function(data){
console.log('Data did not have any locations.')
}
});
}
Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:
$(document).ready(function() {
var today = moment();
var token = url("#access_token");
$.getJSON(dsu + "oauth/check_token?token=" + token)
.done(function(data) {
var username = data["user_name"];
var device = 'android';
var date = url("#date")? moment(url("#date")).toDate() : new Date();
var redraw = function(){
var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
};
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: test, //******* I want to the array to be rendered here.
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
})
.fail(function() {
console.log("Fail!");
});
I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.
Thank you very much! Any help is welcome!
The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
}
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: location_events,
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
}

Categories