Dynamics CRM 2011 · Javascript · JQuery · JSON · OData · REST

CRM 2011 Accessing REST Endpoints using JavaScript JSON JQuery on CRM Forms

REST Endpoints

CRM 2011 introduced a new way to access its data via REST endpoints:

http://localhost:5555/AdventureWorksCycle/XRMServices/2011/OrganizationData.svc

To access the entity collection, we will need to add <EntityName>Set, for example:

http://localhost:5555/AdventureWorksCycle/XRMServices/2011/OrganizationData.svc/ContactSet

To access an individual record, we can use:

http://localhost:5555/AdventureWorksCycle/XRMServices/2011/OrganizationData.svc/ContactSet(guid’CD3EACD3-5496-P091-5AB1-98232DC3239B’)

A simple query:

http://localhost:5555/AdventureWorksCycle/XRMServices/2011/OrganizationData.svc/ContactSet(guidCD3EACD3-5496-P091-5AB1-98232DC3239B‘)?$select=FullName

Codeplex has a great tool for constructing query here.

JSON and JQuery

Once you got your query, you need to have json2.js and jquery1.4.1.min.js library. You can search it online or in your CRM 2011 sdk example codes.

You will need to import this as a web resource into your solution.

To use it, simply add to your form resource so that it appears in this order:

  1. jquery1.4.1.min.js
  2. json2.js
  3. yourcustomscript.js

The Code

To use the query, simply use this template:

$.ajax({
       type: "GET",
       contentType: "application/json; charset=utf-8",
       datatype: "json",
       url: odataSelect,
       beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
       success: function (data, textStatus, XmlHttpRequest)
           {
               // Use only one of these two methods

               // Use for a selection that may return multiple entities
               ProcessReturnedEntities(data.d.results);

               // Use for a single selected entity
               ProcessReturnedEntity(data.d);

           },
       error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
   });
function ProcessReturnedEntities(ManyEntities)
{
  for( i=0; i< ManyEntities.length; i++)
  {
     var oneEntity = ManyEntities[i];
     var fullName = oneEntity.FullName;
  }
}

function ProcessReturnedEntity(OneEntity)
{
     var fullName = OneEntity.FullName;
}

This post has been summarized from a really brilliant post here.

Cheers – Sy

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s