Send a username and age - ajax

I'm new with ajax . I appriciate if you help me to Write an ajax request (in javascript) from the client to the server that sends a username and age and at the end prints to the browser's log success or failure depending on the returned value
<script>
var dob = new Date("06/24/2008");
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
document.write("Age of the date entered: " + age + " years");
</script>

Related

How to read a time in googlespreadsheet with google apps script?

After hours spent to identify a rational or a solution, my hope is now with this community !
I'm desesperatly trying to get ("read") a time entered by user in a google spreasheet and to use it correctly in a google apps script for example to create google calendar event.
The desired format is "HH:mm"
My starting point is the google apps script example provided on https://developers.google.com/apps-script/quickstart/forms
From this example I modified the parameters of the spreasheet (sorry for the french!) using the "Change locale and time zone" instructions :
settings illustration
I also changed the display format of the columns 'C' and 'D' to not have the AM/PM put in the initial example:
Start Time End Time
13:00:00 14:55:00
13:00:00 14:55:00
...
To enable debug in script editor, I removed "_" at the end of setUpConference (line 14).
I launched the script "setUpConference" in debug to check the values read from the datasheet.
My surprise is to have for the first data line
Ethics for monsters 5/15/2013 13:00:00 14:55:00 Rm 323: Minotaur's Labyrinth
the corresponding data of the variable "session"
["Ethics for monsters", (new Date(1368568800000)), (new Date(-2209115361000)), (new Date(-2209108461000)), "Rm 323: Minotaur's Labyrinth"]
and sessions[2] is showned in the script editor as:
Sat Dec 30 1899 13:50:39 GMT+0100 (CET)
I understand that having only "time" (HH:mm), the date is incomplete (so the 1899 day) but how to obtain the time "13:00:00" rather than this strange "13:50:39" ?
Ps: my calendar time zone is also GMT+0100 (CET)
some edits with more information:
I share the google spreadsheet I used for test
I simplified the code of my google app script to focus on the issue (initial code was the one provided by google on https://developers.google.com/apps-script/quickstart/forms
/**
* A special function that inserts a custom menu when the spreadsheet opens.
*/
function onOpen() {
var menu = [{name: 'Set up conference', functionName: 'setUpConference'}];
SpreadsheetApp.getActive().addMenu('Conference', menu);
}
/**
* A set-up function that uses the conference data in the spreadsheet to create
* Google Calendar events, a Google Form, and a trigger that allows the script
* to react to form responses.
*/
function setUpConference() {
/* if (ScriptProperties.getProperty('calId')) {
Browser.msgBox('Your conference is already set up. Look in Google Drive!');
}*/
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Conference Setup');
var range = sheet.getDataRange();
var values = range.getValues();
setUpCalendar(values, range);
}
/**
* Creates a Google Calendar with events for each conference session in the
* spreadsheet, then writes the event IDs to the spreadsheet for future use.
*
* #param {String[][]} values Cell values for the spreadsheet range.
* #param {Range} range A spreadsheet range that contains conference data.
*/
function setUpCalendar(values, range) {
// comment cal for debug
//var cal = CalendarApp.createCalendar('Test Conference Calendar');
for (var i = 1; i < values.length; i++) {
var session = values[i];
var title = session[0];
Logger.log("i= "+i+" - "+ "session[2]= " + session[2] + " | session[3] =" + session[3] );
// This formats the date as Greenwich Mean Time in the format
// year-month-dateThour-minute-second.
var formattedHour = Utilities.formatDate(session[2], "GMT+1", "HH:mm");
Logger.log("formattedHour = "+formattedHour);
var start = joinDateAndTime(session[1], session[2]);
var end = joinDateAndTime(session[1], session[3]);
var options = {location: session[4], sendInvites: true};
// comment cal and event creation
/*var event = cal.createEvent(title, start, end, options)
.setGuestsCanSeeGuests(false);
session[5] = event.getId();*/
}
range.setValues(values);
}
/**
* Creates a single Date object from separate date and time cells.
*
* #param {Date} date A Date object from which to extract the date.
* #param {Date} time A Date object from which to extract the time.
* #return {Date} A Date object representing the combined date and time.
*/
function joinDateAndTime(date, time) {
date = new Date(date);
date.setHours(time.getHours());
date.setMinutes(time.getMinutes());
return date;
}
As linked in some of the comments sheets and JS use different date epochs and they don't always play nice.
change the var values = range.getValues(); to var values = range.getDisplayValues();
this will force it to grab the cells values as string.
changing your date join function as follows will make it handle the strings(may need to ensure the dates in your spread sheet to have leading zeros):
function joinDateAndTime(date, time) {
var t = new Date(date);
t.setHours(parseInt(time.substring(0, 2)));
t.setMinutes(parseInt(time.substring(3, 5)));
return t;
}

Validate End date is greater than start date in CRM 2015

I want to validate Start date and End date how should I write in web resource?
I have tried some code but it doesn't work. The function is continuously repeating after some time. But it should be stop once executed.
Please help me on this.
function ValidateEndDate(econtext)
{
var sdate = Xrm.Page.getAttribute("new_startdate");
var edate = Xrm.Page.getAttribute("new_enddate");
var eventArgs = econtext.getEventArgs();
if (sdate.getValue() > edate.getValue())
{
alert("End date should be greater than");
sdate.setValue(null);
eventArgs.preventDefault();
}
}

How can I make a CakePHP 3 time object remain consistent between AJAX and PHP?

When I load a page with a Time object and echo it out on the page through PHP, I get this:
<?= $user->last_login ?>
// 12/30/14, 5:21 pm
When I load data through ajax, it's returned to me like this:
console.log(response.user.last_login);
// 2014-12-30T17:21:31+0000
I haven't set anything different from the default CakePHP 3 setup, and I need events that are added to the page (returned via ajax) to be in the same time format as events that were pulled on page load (return via PHP).
The default output in string format for Time objects is controlled by the setToStringFormat method http://book.cakephp.org/3.0/en/core-libraries/time.html#setting-the-default-locale-and-format-string
It is a good practice to not hardcode a format there, but to only change the current locale so that the right format is selected for you,
But the format that is used to encode to json is not possible to control it via configuration as it is a standard that dates should be presented in such format when encoded in a JSON API. Instead, what you can do is alter the jsonSerialize method in your User entity:
public function jsonSerialize() {
$toEncode = parent::jsonSerialize();
return ['last_login' => (string)$this->last_login] + $toEncode;
}
What it does is converting to string the last_login property before it is encoded to json. Converting to string will then use the globally configured toString format.
You can convert the format of the date using the javascript Date object
JSFiddle
var date = new Date(response.user.last_login)
//returns a timestamp of 1419960091000
var n = date.getTime();
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
//increment the month by 1 as it starts from 0
var year = date.getFullYear();
year = year.toString().substr(2,2);
//this removes the first 2 characters to give yy, remove the above line for yyyy
var hours = date.getHours();
var minutes = date.getUTCMinutes();
var period='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12){
hours=hours%12;
//remove the above line for 24 hour format
period='pm';
}
Now you can piece together the date in the required format
var last_login = day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ' ' + period;
//gives 30/12/14 5:21 pm
Hope this helps!

Rails Auto-populate form field based off of date input

I have a Rails 3.2.18 app where in my form I have a field for age (int) and date of birth (datetime). I will be using a simple jQuery date picker to select the DOB.
Here's what I want to happen.
The first field is the DOB (Date of birth). I want to select that, and as soon as it's selected I'd like to calculate the age and automatically fill the age field based off of that selection.
I think I can do it somehow by creating a method on the model that calculates the age, but I'm not sure how to populate it in the age field. Perhaps some Javascript or something?
Any help would be greatly appreciated.
Below is a method I wrote for another app that calculates age based on DOB and can be used in a view:
def age(dob)
now = Time.zone.now.to_date
now.year - patient_dob.year - ((now.month > patient_dob.month || (now.month == patient_dob.month && now.day >= patient_dob.day)) ? 0 : 1)
end
What you are suggesting is not possible to do in Ruby. You can use JavaScript.
It's not possible to calculate the age, based on user input, without first traveling to the server, calculating the age, and then rendering the result to the client. The model has no knowledge of the date that the user puts in; this is, unless you submit the form, of course.
It's possible to submit the form via Ajax. For example, some sites let you fill in a zip code, and then they prefil the address for you. What is really happening is, behind the scenes, the browser is sending an ajax request to a server that returns an address.
In your case you shouldn't have to do that since calculating the age in JavaScript is very easy. It's also quicker to do it on the client since it saves you the round trip to the server.
Take a look at this answer which shows you how to calculate a persons age based on an input date.
If you are using Rails you will likely be using jQuery. In which case you can do something like this:
$('#date_input').on('change', function () {
date = $(this).val();
age = getAge(date);
$('#age_input').val(age);
});
# This is taken directly from this answer: https://stackoverflow.com/a/7091965/276959
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Then, on the server you may want to recalculate the age before you save the data into the database. This is because nothing stops the user from submitting a false age directly. Either by filling it in, or by altering the DOM.
class Person
before_save :set_age
private
def set_age
self.age = # Calculate age here.
end
end
See this answer on how to calculate age using Ruby, which looks identical to the code you have in your question.
This is a more client side javascript way to achieve this with date accuracy using server.
In your rails view when parent page loads
<%= javascript_tag do%>
var currDate = new Date('<%= Date.today%>');
<%end%>
In your js file (i assumed date-picker to be the input selected using date picker.)
function calcAge(dateString) {
var birthDate = new Date(#('date_picker').val());
var age = currDate.getFullYear() - birthDate.getFullYear();
var m = currDate.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && currDate.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Then just need to call calcAge on date selected event and the
return age;
can change to set value on an input field
$('#ageField').val(age);

jQuery validate credit card exp date as future date

I can't seem to get this right, I can get it to catch a past date, but not return true on future date.I just need to validate my form's Credit Card Expiration Date as being in the future, this isn't working, any ideas? the date has to be in the format MM/YYYY with a "/" in between them.
$.validator.addMethod(
"FutureDate",
function(value, element) {
var startdatevalue = (.getMonth/.getYear);
return Date.parse(startdatevalue) < Date.parse($("#ExpirationDate").val());
},
"End Date should be greater than Start Date."
);
You're not actually getting it to catch a past date. If you're passing a date like this "11/2010" to your Date.parse(), it is returning NaN (or Not a Number) which is the logical equivalent to returning false.
Try doing this to see what I mean:
alert( Date.parse('11/2010') );
If you add a day number, it should work. Something like:
var startdatevalue = '11/1/2010';
Of course, this example uses a hard coded date. If the values are stored as 11/2010, you could try something like this:
// Get the index of the "/"
var separatorIndex = value.indexOf('/');
// Add "/1" before the separatorIndex so we end up with MM/1/YYYY
var startDate = value.substr( 0, separatorIndex ) + '/1' + value.substr( separatorIndex );
// Do the same with the expiration date
var expDate = $("#ExpirationDate").val();
separatorIndex = expDate.indexOf('/');
expDate = expDate.substr( 0, separatorIndex ) + '/1' + expDate.substr( separatorIndex );
// Return the comparison
return Date.parse(startDate) < Date.parse(expDate);

Resources