marwen
marwen

Reputation: 33

add new record in CRM using web API

I am trying to add records to CRM using Javascript but getting:

401 Unauthorized Error.

My question is how to get the token and use it inside the JavaScript function.

$(document).ready(function() {
  $("#Save").click(function() {
    var ProductDetails = new Object();
    ProductDetails.ProductName = $("#txt_productName").val();
    ProductDetails.ProductDetail = $("#txt_desc").val();

    $.ajax({
      url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
      type: "Post",
      dataType: 'JSON',
      data: ProductDetails,
      contentType: 'application/x-www-form-urlencoded',
      success: function(data) {
        alert('Updated Successfully');

      },
      error: function(request, status, error) {
        alert(request.status);
      }
    });
  });
});

Upvotes: 1

Views: 212

Answers (2)

André Cavaca
André Cavaca

Reputation: 530

You have to add a header with the bearer token like this:

$.ajax({
(...)
headers: {
  "Authorization": "Bearer " + token
},
(...)

In order to get a token you have to register an application in Azure Active Directory first, in the same tenant as your Dynamics 365 instance. Check this link if you need a thorough step by step guide to do it.

After registering you application in AAD you also have to add some code to do the authentication with Azure and getting the token. ADAL.js does this job for you, but keep in mind that it prompts the user to manually add his username and password in a office 365 popup. This is called interactive authentication and as far as I know it can't be avoided.

For a full HTML + JS working example click here.

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

You need add Authorization information in Http Header. Here is an example if you use JWT.

$(document).ready(function() {
  $("#Save").click(function() {
    var ProductDetails = new Object();
    ProductDetails.ProductName = $("#txt_productName").val();
    ProductDetails.ProductDetail = $("#txt_desc").val();

    $.ajax({
      url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
      type: "Post",
      headers: {
        'Accept':'application/json',
        'Content-Type':'application/json',
        'Authorization':'Bearer your token here'
     },
      dataType: 'JSON',
      data: ProductDetails,
      contentType: 'application/x-www-form-urlencoded',
      success: function(data) {
        alert('Updated Successfully');

      },
      error: function(request, status, error) {
        alert(request.status);
      }
    });
  });
});

Upvotes: 0

Related Questions