Main | Creating A Bootable USB Flash Drive »

Making Updates to SharePoint from JavaScript

While working on a project involving SharePoint, our effort to provide a better UI required making some updates from JavaScript. If you make an attempt at this you are likely to get the following error.

Microsoft.SharePoint.SPException was unhandled by user code Message="The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again." Source="Microsoft.SharePoint"

What's going on is SharePoint trying to prevent cross-site scripting. You will find many articles saying to wrap your update setting AllowUnsafeUpdates like below.

myWeb.AllowUnsafeUpdates = true;
// Call Update();
myWeb.AllowUnsafeUpdates = false;

Here you can find an explanation of AllowUnsafeUpdates.

I opted to not use AllowUnsafeUpdates. Instead I went with the POST approach. This requires a control added to your page.

<sharepoint:formdigest runat="server"/>

MSDN states: “To make posts from a Web application that modify the contents of the database, you must include the FormDigest control in the form making the post. The FormDigest control generates a security validation, or message digest, to help prevent the type of attack whereby a user is tricked into posting data to the server without knowing it.

So now your page will have a few new additions to it. Namely a small JavaScript call on form submit and a hidden input field with id=”__REQUESTDIGEST”. The OnSubmit call is to WebForm_OnSubmit() and will populate the value of the hidden input field. All that is needed is for your JavaScript code to call this method itself and then send the key-value of __REQUESTDIGEST in along with your post data.

PrintView Printer Friendly Version

EmailEmail Article to Friend

References (2)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>