Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows Server

Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - REST and OData (part 3) - Creating, Updating, and Deleting

8/17/2014 9:29:30 PM

Creating, Updating, and Deleting

The REST endpoints also accept requests to create, update, and delete data using POST, PUT, and PATCH commands.

  • POST is used for creating data
  • PUT is used for updating (all property values specified)
  • PATCH is used for updating (specified properties only)

When using any of the preceding commands from JS running on a SharePoint page, you also must include the form digest from the page in the appropriate HTTP header:

X-RequestDigest: formDigest

You can get the formDigest from the object returned from a POST call to /_api/contextinfo, or if you are building a SharePoint-hosted app then you can simply get the value of the formDigest with this JQuery function:

$('#__REQUESTDIGEST').val()

You are then ready to send your create, update, or delete command to SharePoint. To practice doing so, take a look at the following activity.


TRY IT OUT: Creating a New List in the Host Web

In this example you use a SharePoint-hosted app using the Napa Office 365 Development Tools and use the REST/OData API to create a new list in the host Web. You must have the Napa application installed from the Office 365 marketplace prior to starting this exercise. The full JavaScript source for this exercise is available in the code download in the MyODataJavaScriptApp.js file.

1. Ensure you have Napa Office 365 Development Tools installed in your development site in Office 365.

2. Click Site Contents in your site navigation to see a list of all apps installed in your site.

3. Locate “Napa” Office 365 Development Tools in the list and click it, as shown in Figure 2.

FIGURE 2

image

4. Click Add New Project in the screen that appears.

5. Select App for SharePoint and enter MyODataJavaScriptApp in the Project name box. Click Create to continue. Napa creates a set of template files and folders for you. Explore the structure and get familiar with the layout of the application.

6. In the lower left of the window click the wrench icon to open the Property panel for your application as shown in Figure 3.

FIGURE 3

image

7. Click the Permissions tab and set the permissions for Web under Content to Full Control.

8. Open the Scripts folder and then open the App.js file. This default file contains the JavaScript for your application.

9. Add the following code to the bottom of the file. This helps you get the various parameters that were passed to the page from the querystring:
function getParams() {
var params = {};
location.search.split('?')[1].split('&').forEach(function (param) {
var key = param.split('=')[0],
val = decodeURIComponent(param.split('=')[1]);
params[key] = val;
});
return params;
}
10. Replace the sharePointReady() function with the following. This code loads the SP.RequestExecutor.js JavaScript file that helps with cross-domain calls. The app needs this to call into the host Web because it’s on a different domain name:
var params;
var scriptbase;

function sharePointReady() {
context = new SP.ClientContext.get_current();
params = getParams();
scriptbase = params.SPHostUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
}
11. Add the following new function. This uses a POST command to post a JSON payload with the new list information to the host web’s REST API:
function execCrossDomainRequest()
{
var executor;
executor = new SP.RequestExecutor(params.SPAppWebUrl);

var data = JSON.stringify({ '__metadata': { 'type': 'SP.List' },
'AllowContentTypes': true, 'BaseTemplate': 100,
'ContentTypesEnabled': true, 'Description': 'My list description',
'Title': 'My New List' });

var requestUri = params.SPAppWebUrl +
"/_api/SP.AppContextSite(@target)/web/lists?@target='" + params.SPHostUrl + "'";

executor.executeAsync(
{
url: requestUri,
method: "POST",
body: data,
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"content-length": data.length,
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
success: successHandler,
error: errorHandler
}
);
}

function successHandler(data) {
alert('success');
}

function errorHandler(data, errorCode, errorMessage) {
alert("Failed :( Error:" + errorMessage);
}
12. Click the Run Project button in the bottom left of the window to test out the application. When it completes a message appears like the one shown in Figure 4.

FIGURE 4

image

13. Right-click the launch link and open your app in a new window to start your application. When you are prompted to trust your app, click Trust It to continue.

14. A JavaScript alert message appears, stating “Success.” The app has created the list in the host Web.

15. Navigate to the host website by clicking the title of your site in the navigation.

16. Click Site Content to see a list of the apps/lists in your site. You can see the new list called My New List that your app created, as shown in Figure 5.

FIGURE 5

image

How It Works

In this exercise you created a SharePoint-hosted app that created a new list in the host or parent Web. To do this it used the REST/OData API and a POST command to post the creation information as a JSON payload in the request. Because the request was from one domain to another, you used the SP.RequestExecutor framework to proxy the call via the app Web to the host Web. This step was necessary due to the cross-domain security boundary browsers put on JavaScript.
The JSON payload consisted of a JSON representation of an SP.List object, along with the properties needed for creation such as the BaseTemplate ID and the Title.
By making a POST request along with this JSON to the /_api/SP.AppContextSite(@target)/web/lists URI, SharePoint proxies the request to the host Web for you along with the JSON. Because the request is a POST SharePoint knows you want to create something. SharePoint knows you want to create a list because the URI specifies the /web/list REST endpoint. SharePoint looks in the body of the request for the details on the list you want to create and creates it.


WATCH THE JAVASCRIPT CSOM AT WORK WITH FIDDLER
If you are interested in seeing the underlying API calls to SharePoint from the JavaScript CSOM you can do so with a tool called Fiddler. You can download Fiddler from: http://www.fiddler2.com. Using Fiddler you can see all the HTTP traffic between your computer and another such as Sharepoint.com, where Office 365 is hosted. When watching Fiddler look for requests to URLs with paths that end in: /_vti_bin/client.svc/ProcessQuery. You will see XML payloads being sent to SharePoint along with JSON responses.
Other -----------------
- Sharepoint 2013 : Integrating Apps for Office with SharePoint (part 2) - Apps for Office Integrated with an App for SharePoint
- Sharepoint 2013 : Integrating Apps for Office with SharePoint (part 1) - Standalone Apps for Office
- Sharepoint 2013 : The Office JavaScript Object Model (part 3) - App Security
- Sharepoint 2013 : The Office JavaScript Object Model (part 2) - Functional Capabilities by Office Client,Mailbox-based Apps
- Sharepoint 2013 : The Office JavaScript Object Model (part 1) - Document-based Apps
- SQL Server 2012 : Understanding Latches and Spinlocks (part 3) - Latching Example - With Latching
- SQL Server 2012 : Understanding Latches and Spinlocks (part 2) - Latching Example - Without Latching
- SQL Server 2012 : Understanding Latches and Spinlocks (part 1) - Latching Example
- SQL Server 2012 : Latches and Spinlocks - Symptoms (part 2) - Measuring Latch Contention, Measuring Spinlock Contention , Contention Indicators
- SQL Server 2012 : Latches and Spinlocks - Symptoms (part 1) - Recognizing Symptoms
 
 
Top 10 video Game
-   Minecraft Mods - MAD PACK #10 'NETHER DOOM!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #9 'KING SLIME!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #2 'LAVA LOBBERS!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #3 'OBSIDIAN LONGSWORD!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Total War: Warhammer [PC] Demigryph Trailer
-   Minecraft | MINIONS MOVIE MOD! (Despicable Me, Minions Movie)
-   Minecraft | Crazy Craft 3.0 - Ep 3! "TITANS ATTACK"
-   Minecraft | Crazy Craft 3.0 - Ep 2! "THIEVING FROM THE CRAZIES"
-   Minecraft | MORPH HIDE AND SEEK - Minions Despicable Me Mod
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 92 "IS JOE DEAD?!"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 93 "JEDI STRIKE BACK"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 94 "TATOOINE PLANET DESTRUCTION"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 95 "TATOOINE CAPTIVES"
-   Hitman [PS4/XOne/PC] Alpha Gameplay Trailer
-   Satellite Reign [PC] Release Date Trailer
Popular tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 windows Phone 7 windows Phone 8
programming4us programming4us
 
Popular keywords
HOW TO Swimlane in Visio Visio sort key Pen and Touch Creating groups in Windows Server Raid in Windows Server Exchange 2010 maintenance Exchange server mail enabled groups Debugging Tools Collaborating
programming4us programming4us
PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Trailer game
 
programming4us
Natural Miscarriage
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Game Trailer