Google Calendar API Freebusy JQuery $ .post gets error 400 (failed request)
I am new to javascript, JQuery and Google API, so the answer to this question might be a very simple thing that I am missing. I have checked all the available Google Calendar Freebusy questions on this site, but I am unable to customize their answers in any way.
I am trying to write a script for an html page that checks an open free calendar request. Google states that the HTTP request should be
POST https://www.googleapis.com/calendar/v3/freeBusy
with request body
{
"timeMin": datetime,
"timeMax": datetime,
"timeZone": string,
"groupExpansionMax": integer,
"calendarExpansionMax": integer,
"items": [
{
"id": string
}
]
}
My current html page has the latest jquery library and script I'm writing. Calling the script on the page results in an error Failed to load resource: the server responded with a status of 400 (Bad Request)
. Additional error information returns a parse error with"This API does not support parsing form-encoded input."
My script looks like this:
(function ($) {
$.GoogleCalendarFreebusy = function (options) {
var defaults = {
apiKey: '[projectkey]',
getID: '[id]@group.calendar.google.com',
element: '#div'
};
options = $.extend(defaults, options);
$.post('https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
{"items":[{"id": getID }],"timeMin":"2015-04-10T14:15:00.000Z","timeMax":"2015-04-20T23:30:00.000Z"}, "null", "json")
.done(function(data) {
loaded(data);
});
function loaded(data) {
var status = data.calendars[getID].busy;
console.log(status);
if(status.length !== 0 ) {
for(var i = 0; i < status.length; i++) {
var statusEntry = status[i];
var startTime = statusEntry.start;
var endTime = statusEntry.end;
}
var now = new Date().toISOString();
var element = options.element ;
var name = element.substr(1);
if (now > startTime && now < endTime){
$(options.element).append( 'Available!');
}
else {
$(options.element).append( 'Unavailable!');
}
} else {
$(options.element).append('Unavailable!');
}
}
};
})(jQuery);
My request is getting the correct response in Google Explorer "Try it" , so I think it might be a javascript / json request error I "Skip?" Thanks in advance for your help and advice.
source to share
Google Calendar API. Requests must include JSON content to avoid the above error. Processing the POST as an AJAX request with the specified contentType resolves this error.
$.ajax({
url: 'https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
type: 'POST',
data: '{"items":[{"id": "[id]@group.calendar.google.com"}], "timeMin": "2015-04-10T14:15:00.000Z", "timeMax": "2015-04-20T23:30:00.000Z"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: 'null'
})
Thanks for the suggestions!
source to share