Create, Update, Delete records from Power Portals using Web API
Wrapper AJAX Function
(function(webapi, $){
function safeAjax(ajaxOptions) {
var deferredAjax = $.Deferred();
shell.getTokenDeferred().done(function (token) { // add headers for AJAX if (!ajaxOptions.headers) { $.extend(ajaxOptions, { headers: { "__RequestVerificationToken": token } }); } else { ajaxOptions.headers["__RequestVerificationToken"] = token; } $.ajax(ajaxOptions) .done(function(data, textStatus, jqXHR) { validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve); }).fail(deferredAjax.reject); //AJAX }).fail(function () { deferredAjax.rejectWith(this, arguments); // on token failure pass the token AJAX and args }); return deferredAjax.promise(); } webapi.safeAjax = safeAjax; })(window.webapi = window.webapi || {}, jQuery)
Create Record
webapi.safeAjax({
type: "POST",
url: "/_api/accounts",
contentType: "application/json",
data: JSON.stringify({
"name": "Sample Account"
}),
success: function (res, status, xhr) {
//print id of newly created table record
console.log("entityID: "+ xhr.getResponseHeader("entityid"))
}
});
Update Record
webapi.safeAjax({
type: "PATCH",
url: "/_api/accounts(00000000-0000-0000-0000-000000000001)",
contentType: "application/json",
data: JSON.stringify({
"name": "Sample Account - Updated"
}),
success: function (res) {
console.log(res);
}
});
Delete Record
webapi.safeAjax({
type: "DELETE",
url: "/_api/accounts(00000000-0000-0000-0000-000000000001)",
contentType: "application/json",
success: function (res) {
console.log(res);
}
});
Deactivate Record
webapi.safeAjax = safeAjax; })(window.webapi = window.webapi || {}, jQuery) if (confirm('Update?')) { alert('Thanks for confirming'); webapi.safeAjax({ type: "PATCH", url: "/_api/tk_inspections(e4c23961-61f5-ea11-a815-000d3ad20d1d)", contentType: "application/json", data: JSON.stringify({ "statecode": 1, "statuscode": 821350004 //Cancelled - custom new inactive value }), success: function (res) { alert("Yay!") } });
Read complete article here.