3

I am having trouble with a REST call using jQuery on Office 365 and was wondering if you guys have ever experienced something similar and could give me some hints?

What I am trying to achieve is to get "My Today's Events" from my calendar on Office 365 using REST API and jQuery, however, I haven't had any success so far.

Here is my code:

function rest_call(){   
try
{
    var calendarUrl = "https://outlook.office365.com/ews/odata/Me/Events";
    var calendarItems_html = "<div class='title'> Today's Schedule </div>";

    $.ajax({
        url: calendarUrl,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                $.each(data.value, function (i, item) { 
                     if(item.IsAllDay)                       
                        calendarItems_html += "<div class='item'><img src='/sites/mytheme/Style%20Library/mytheme/images/schedule-arrow.png' alt=''/><span class='time'> " + getDate(item.Start) + " </span><span class='content'>" + item.Subject + "</span></div>";          
                     else {                     
                         calendarItems_html += "<div class='item'><img src='/sites/mytheme/Style%20Library/mytheme/images/schedule-arrow.png' alt=''/><span class='time'> " + getTime(item.Start) + "&nbsp;-&nbsp;" + getTime(item.End) + " </span><span class='content'>" + item.Subject + "</span></div>";
                        }
                    }); 

                $(".schedule").append(calendarItems_html);
            },
            error: function (err) {
                $(".schedule").append(err);
            }
        });
}
catch(err)
{
    $(".schedule").append(err);    
}

}

function getDate(ddate){
  var dDateHours= ddate.substring(0,10);
  return dDateHours;
}

function getTime(ddate){
  var dDateHours= ddate.substring(16,11);
  return dDateHours;
}

This code only returns data if the site and outlook.office365.com are added into one security zone (in IE) and the security settings are set to Low!

Could you please let me know what my mistake is and what's the right way of achieving this goal?

  • I am facing similar issue so wanted to know if you were able to find any resolution for your issue – user33619 Sep 19 '14 at 17:15
0

I believe you would need to go through the whole oAuth flow of getting tokens to validate and authorize the user. Matthias has an indepth article on this on his blog, and there is a JS library available to help with the oAuth flow called ADAL.

0

You need an authentication token(access toke) that you then pass to our Outlook REST query to get the events in OAuth flow.This will authenticate with OAuth2 using the Client ID and Reply UL from our Azure AD settings.

Pass through the request header

$.ajax({
    url: "https://outlook.office.com/api/v1.0/me/calendarview?startDateTime="+startString+"&endDateTime=" + endString,    
    type: "GET",
    dataType: "json",
    headers: {
        Accept: "application/json;odata.metadata=minimal;odata.streaming=true",
        'Authorization': "Bearer " + token
    }    
});

Full code example are here.

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>

<div id='calendar'></div>

<script type="text/javascript">
    //check to see if we have a token in the URL. If we don't, then the user has not been
    //authenticated
    var authenticated = (window.location.href.split("#access_token=")[1]!=undefined);
    if (!authenticated)
    {
        //authenticate user using OAuth
        requestToken();    
    }
    else
    {
        //there is a token in the URL. Let's retrieve from the query string
        var token = window.location.href.split("#access_token=")[1].split("&")[0];
        //Pass the token to the function to call the Outlook REST API
        GetOutlookEvents(token);
    }


function requestToken() { 
    // Change clientId and replyUrl to reflect your app's values 
    // found on the Configure tab in the Azure Management Portal

    var clientId = '<get your own client id>';        
    var replyUrl    = 'https://test.sharepoint.com/SitePages/Home.aspx'; 
    var endpointUrl = 'https://outlook.office365.com/ews/odata/Me/Events';
    var resource = "https://outlook.office365.com/";        
    var authServer  = 'https://login.windows.net/common/oauth2/authorize?';  
    var responseType = 'token'; 

    var url = authServer + 
            "response_type=" + encodeURI(responseType) + "&" + 
            "client_id=" + encodeURI(clientId) + "&" + 
            "resource=" + encodeURI(resource) + "&" + 
            "redirect_uri=" + encodeURI(replyUrl); 

    //redirect user to the OAuth URL. The user will be redirected back to the page
    //unless some error occurs that prevents it
    window.location = url; 
}

function GetOutlookEvents(token) { 
        //instantiate the FullCalendar calendar
          $('#calendar').fullCalendar({
            height: 450,
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            disableDragging: true,
            editable: false,
            events: function(start, end, callback) {
                //This functon executes every time the calendar changes views.
                //the "start" and "end" variables contain the date values
                //for the first and last day visible in the calendar.
                //we need to convert these dates to a formate that the
                //REST query recognizes
             var startString = start.getUTCFullYear() +"-"+
                              ("0" + (start.getUTCMonth()+1)).slice(-2) +"-"+
                              ("0" +start.getUTCDate()).slice(-2) + "T" +
                              ("0" +start.getUTCHours()).slice(-2) + ":" +
                              ("0" +start.getUTCMinutes()).slice(-2) + ":" +
                              ("0" +start.getUTCSeconds()).slice(-2) + "Z";

             var endString = end.getUTCFullYear() +"-"+
                              ("0" + (end.getUTCMonth()+1)).slice(-2) +"-"+
                              ("0" +end.getUTCDate()).slice(-2) + "T" +
                              ("0" +end.getUTCHours()).slice(-2) + ":" +
                              ("0" +end.getUTCMinutes()).slice(-2) + ":" +
                              ("0" +end.getUTCSeconds()).slice(-2) + "Z";

                //execute the outlook REST query passing in the token in the header
                var call = $.ajax({
                    url: "https://outlook.office.com/api/v1.0/me/calendarview?startDateTime="+startString+"&endDateTime=" + endString, 
                    type: "GET",
                    dataType: "json",
                    headers: {
                        Accept: "application/json;odata.metadata=minimal;odata.streaming=true",
                        'Authorization': "Bearer " + token
                    }

                });
                call.done(function (data,textStatus, jqXHR){

                    var events = [];
                    //loop through the returned events and push them
                    //into the events array that will be displayed in the calendar.
                    for (index in data.value)
                    {
                        events.push({
                                    title: data.value[index].Subject,
                                    start: data.value[index].Start
                                });
                    }

                    callback(events);

                });

                call.fail(function (jqXHR,textStatus,errorThrown){
                    alert("Error retrieving events: " + jqXHR.responseText);
                });                                
            }
        });
}    
</script>
-4

Development Steps Required JS

<!-- Reference jQuery on the Google CDN -->
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- Reference SPServices on cdnjs (Cloudflare) -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript">
CAML Query
CAML query for Get current month events from Calendar List
CAMLQuery: "<Query>" +
            "<Where>" +
                "<DateRangesOverlap>" +
                    "<FieldRef Name='EventDate' />" +
                    "<FieldRef Name='EndDate' />" +
                    "<FieldRef Name='RecurrenceID' />" +
                    "<Value Type='DateTime'>" +
                        "<Month />" +
                    "</Value>" +
                "</DateRangesOverlap>" +
            "</Where>" +
            "<OrderBy>" +
                "<FieldRef Name='EventDate' />" +
            "</OrderBy>" +
        "</Query>",
    CAMLQueryOptions: "<QueryOptions>" +
            "<CalendarDate>" + startDate + "</CalendarDate>" +
            "<RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>" +
            "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
        "</QueryOptions>

Call SPServices · Using SPServices we can get items form Calendar list · We have to apply the above CAML query while get items from list · Based on list we will generate the table which has event info · Add the hyperlink for view full calendar view

<a
href="JavaScript:var options=SP.UI.$create_DialogOptions();
options.url='https://collaboration/sites/ENF/MicroCap/Lists/Calendar/calendar.aspx';
options.title = 'Monthly Calendar';
options.height = 500;
void(SP.UI.ModalDialog.showModalDialog(options))">Monthly View</a>

Implementation Create CurrentMonthlyView.html which has the above info SPSevices call and place this into style libray Create content editor webpart into home page and add the reference of CurrentMonthlyView.html file into it. Verification Steps

Check display meeting events are associated to current month or not

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.