Posted in Code Snippets, CRM, JavaScripts, OData Call

Odata Call To update field with WebApI

Odata Call To update field with WebApI :

Updated Fields are “new_test1” and “new_test2” .

function myFunction() {
debugger;
// new_test1, new_test2 Schema name of updated fields and new_customs entity SchemaName name
var entity = {};
entity.new_test1= "gb";
entity.new_test2= "sr";

var entityname =window.parent.Xrm.Page.data.entity.getEntityName();
var RecordId= window.parent.Xrm.Page.data.entity.getId().replace("{","").replace("}","");

//OdataCall
var req = new XMLHttpRequest();
req.open("PATCH", window.parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.0/"+entityname+ "s("+RecordId + ")", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function () {
 if (this.readyState === 4) {
 req.onreadystatechange = null;
 if (this.status === 204) {
 //Success - No Return Data - Do Something
 
 }
 else {
 alert(this.statusText);
 }
 }
};
req.send(JSON.stringify(entity));
window.parent.Xrm.Page.data.refresh();
}