403 Forbidden when deleting SPWeb (JSOM) REST call Office365

When attempting to DELETE a SharePoint sub web within some included JavaScript (as opposed to a SharePoint App), you can simply call a REST endpoint, and pass the ‘DELETE’ verb as a HTTP header.

This is using the $.ajax method of jQuery.

You just need to use the URL of the subweb you want to delete – with the “_api/web” suffix.

var urlToDelete = 'http://tenant.sharepoint.com/sites/corp/web/subweb1/_api/web';

And – to then do a call to the REST endpoint, you just construct JavaScript like this :

$.ajax({
        url: urlToDelete,
        method: 'POST',
        headers: {
            'Accept': 'application/json; odata=verbose', 
            'X-HTTP-Method': 'DELETE'
        },
        success: function (data) {
            alert('success');
        },
        error: function (err) {
            alert('fail');
        }
    }); 

BUT – and this is what caught me out – you might get a “403 Forbidden” error.    If you check using F12 developer tools – you’ll see the error.

The trick is to include the content of the page (hidden variable) – and use as another header :

$('#__REQUESTDIGEST').val()

And so – when you add it all together – you get this – and it works !    and no 403 error…

$.ajax({
        url: urlToDelete,
        method: 'POST',
        headers: {
            'Accept': 'application/json; odata=verbose', 
            'X-HTTP-Method': 'DELETE',
            'X-RequestDigest': $('#__REQUESTDIGEST').val()
        },
        success: function (data) {
            alert('success');
        },
        error: function (err) {
            alert('fail');
        }
    });

If you get a 500 error – it maybe that there are “subwebs” – and you need to delete those first.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s