REST and SharePoint 2010 Quick Start Guide: POST Data with JSON

 

Table of Contents for this Series

This is a short post, I want to provide the JSON version of posting a new meeting entry. You have a couple of similar ways that this can be done – so I’ll cut directly to the code.

The first method is defining an object and posting the serialized results to the calendar. The code looks as follows

Method 1

$(document).ready(function() {

var cal = { Title: "January Team Meeting", StartTime: "2010-01-15T17:00:00", EndTime: "2010-01-15T18:00:00" };

var entry=JSON.stringify(cal);

$.ajax({
          type: "POST",
          url: "http://win-dcbei0i59th/_vti_bin/ListData.svc/Calendar",
          data: entry,
          contentType: "application/json; charset=utf-8",
          error: function(xhr) {
                 alert(xhr.status + ‘: ‘ + xhr.statusText);                                   
             }
      });

});

Method 2

This method allows for creating an object as the starting point, note that we are using the IE 8 built in JSON parser (‘JSON’);

$(document).ready(function() {

var calendar = new Object;

calendar.Title = "January Team Meeting";
calendar.StartTime = "2010-01-16T10:00:00";
calendar.EndTime = "2010-01-16T11:00:00";

var entry=JSON.stringify(calendar);

$.ajax({
          type: "POST",
          url: "http://win-dcbei0i59th/_vti_bin/ListData.svc/Calendar",
          data: entry,
          contentType: "application/json; charset=utf-8",
          error: function(xhr) {
                 alert(xhr.status + ‘: ‘ + xhr.statusText);                                   
             }
      });

});

Results

Results from this method appears as follows – very cool!

image 

Additional Information

IE 8 comes with a ‘native’ JSON serializer and deserializer library, see http://blogs.msdn.com/ie/archive/2008/09/10/native-json-in-ie8.aspx also see

http://www.json.org/ (based on json2.js)

The way I implemented this was to include the following script section in the <head> of my sample page.  This appears as follows

<script src="http://json.org/json2.js" type="text/javascript"></script> (Why? for whatever reason I had trouble with the native one – something glitchy with my setup?)

That’s it for this post – Cheers!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s