Avoid security validation error handling Ajax POST calls in SharePoint 2010

If you have an AJAX call in a SharePoint application that use the method POST to send some form data, and handling such call server side you have to modify a SharePoint item, probably you will come across the following security validation error:

System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

In order to avoid such error you should add the request digest of your form (see here for more details) in the HTTP header of the AJAX message:

var formDigest = $("[name='__REQUESTDIGEST']").val();
jQuery.ajax({
  type: "POST",
  url: window.location.protocol + "//" + window.location.host + "/SomeService",
  data: dataToPass,
  async: false,
  headers: { "X-RequestDigest": formDigest },
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (result) {
    // ...
  }
  error: function (xhr, status, error) {
    // ...
  }
});

While server side you must validate such digest:

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
  using (SPWeb web = site.OpenWeb())
  {
    if (SPUtility.ValidateFormDigest())
    {
      try
      {
        SPListItem item = web.Lists[listId].GetItemById(itemId);

        // Some code that modify the item
        // ...

        // Update the item
        item.SystemUpdate();
      }
      catch (Exception ex)
      {
        // ...
      }

    } // if

  } // using web

} // using site

References

http://www.gsoft.com/en/blog/sharepoint-security-validation-with-jquery-and-wcf-services

http://www.sharepoint.bg/radi/post/Fun-with-HTTP-Handlers-Security-Validations-FormDigest-AllowUnsafeUpdates-jQuery-AJAX-and-POST-parameters-in-SharePoint.aspx

http://msdn.microsoft.com/en-us/library/ms472879.aspx

  • Jason

    Hi Andrea, is there a way to get a new request digest without reloading the page?

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo