AllramEst
AllramEst

Reputation: 1449

Add event to SharePoint calender list with REST _api

Is there anybody that knows how to post events to an SharePoint Online Calender list using Sharepoint REST _api.

I found this post here on stack: link But it uses authorization which I don’t have to use in my case because my app lives inside of sharepoint. I have found docs on how to make CRUD to a outlook calender. But it doesn’t cover sharepoint of course.

This is the code so far:

    function PostToBokningar() {
    var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items`;
    //requestHeaders
    var requestHeaders = {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": jQuery('#__REQUESTDIGEST').val()
    }
    //Data
    var data = {
        __metadata: { "type": "SP.Data.BokningarListItem" },
        Title: "Test title",
        EventDate: moment.utc("2017-12-12 10:00").format('YYYY-MM-DD HH:mm:ssZ'),
        EndTime: moment.utc("2017-12-12 17:00").format('YYYY-MM-DD HH:mm:ssZ'),
        Description: "test description"
    };
    //requestBod
    var requestBody = JSON.stringify(data);
    //Post
    var post = jQuery.ajax({
        url: url,
        type: "POST",
        headers: requestHeaders,
        data: data
    })

}

The error message I get is:

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}

Any suggestions?

Upvotes: 0

Views: 2728

Answers (1)

mikeplate
mikeplate

Reputation: 1149

Yes, you have two errors in your code. You are not sending the stringified json to the REST service. Replace the call to:

var post = jQuery.ajax({
    url: url,
    type: "POST",
    headers: requestHeaders,
    data: requestBody
})

And also, the field for the end of the event is called EndDate and not EndTime, so replace to:

var data = {
    __metadata: { "type": "SP.Data.BokningarListItem" },
    Title: "Test title",
    EventDate: moment.utc("2017-12-12 10:00").format('YYYY-MM-DD HH:mm:ssZ'),
    EndDate: moment.utc("2017-12-12 17:00").format('YYYY-MM-DD HH:mm:ssZ'),
    Description: "test description"
};

Upvotes: 1

Related Questions