Skip to content
← All tips

The safeAjax wrapper to call the Power Pages Web API

Calls to /_api/ that write data need the anti-forgery token (__RequestVerificationToken). Microsoft suggests a small wrapper around $.ajax that adds it for you, and I put it in the site Header so every page can use it:

(function (utilities, $) {
  function safeAjax(ajaxOptions) {
    const deferredAjax = $.Deferred();
    shell.getTokenDeferred().done(function (token) {
      ajaxOptions.headers = ajaxOptions.headers || {};
      ajaxOptions.headers["__RequestVerificationToken"] = token;
      $.ajax(ajaxOptions)
        .done(function (data, textStatus, jqXHR) {
          validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
        })
        .fail(deferredAjax.reject);
    }).fail(function () {
      deferredAjax.rejectWith(this, arguments);
    });
    return deferredAjax.promise();
  }
  utilities.safeAjax = safeAjax;
})((window.utilities = window.utilities || {}), jQuery);

From then on, any page can call utilities.safeAjax({ type: "PATCH", url: "/_api/accounts(" + id + ")", ... }).

You don’t have to define shell.getTokenDeferred() or validateLoginSession, both come with Power Pages. The second one also sends the user back to the login page if their session has expired.

A word of warning from experience: some ad blockers cut these requests off. If nothing seems to happen when you test, turn the blocker off before you start going through your code line by line.

Did it help?

If you need help with this in your project, write to me.

More tips