Monday, March 7, 2016

CRM 2016 WEB API - Create record with Javascript

This is a helper function to create records in CRM 2016 using the WEB API



function CreateRecord2016(entity, entityName){
 try{   
  /* Example of entity : note, all fields in lowercase
   var CRMObject = new Object(); 
   CRMObject.new_name = "test name";   
   CRMObject.new_customfieldname = "test";   
  */
  var req = new XMLHttpRequest()
  req.open("POST",encodeURI(clientURL + "/api/data/v8.0/" + entityName + "s"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("OData-MaxVersion", "4.0");
  req.setRequestHeader("OData-Version", "4.0");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204) {
     var createdRecordId = this.getResponseHeader("OData-EntityId");
     
     result = createdRecordId;
    }
    else {
     var error = JSON.parse(this.response).error;
     //console.log(error.message);
     result = error;
    }
   }
  };
  req.send(window.JSON.stringify(entity)); 

  
  //Asynchronous AJAX function to Create a CRM record using OData 
  return result;
 }catch(err){
  showError(arguments.callee.toString().match(/function\s+([^\s\(]+)/)[1], err.message);
 }
}

function showError(functionName, errorMessage) 
{   
   alert(functionName + ": " + errorMessage);
}

2 comments:

  1. Hi Arturo, I am new to CRM 2016. I am trying to create a HTML web resource with tables and columns. Here I am trying to create account records using Web API. I have created the HTML page but no idea how to create records using JavaScript and call WebAPI. Any suggestion would be a great help.

    ReplyDelete