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();
  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())
        SPListItem item = web.Lists[listId].GetItemById(itemId);

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

        // Update the item
      catch (Exception ex)
        // ...

    } // if

  } // using web

} // using site





  • Jason

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


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


Developed and designed by Netgloo
© 2019 Netgloo