Query Dynamics CRM Through JavaScript

Leave a comment

Using JavaScript, we can send queries to Dynamics CRM to retrieve data. We will go through an example of how to do this.

We will use Xrm.Page.context.getClientUrl() to get the CRM URL. If we run code to get the URL we get:

 var url = Xrm.Page.context.getClientUrl();
 alert("URL: " + url);

We will use this URL to get the full web service URL:

var url = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";

Next, we will use the Id of the record in CRM in our query. We will use an example of Leads, so we will get the lead record id:

var Id = Xrm.Page.data.entity.getId();

Now we will construct the query. The query can pass filters, for example if we wanted to see all leads where the lastname is “Cook”, the query would be:

https://yourcrm.crm.dynamics.com/XRMServices/2011/OrganizationData.svc/LeadSet?$filter=LastName eq 'Cook'

To filter the LeadId our query will be:

https://yourcrm.crm.dynamics.com/XRMServices/2011/OrganizationData.svc/LeadSet(guid'id')

Now, we will use XMLHttpRequest to post to the web service and get our response back as JSON. We will confirm we have an http status of 200 (OK).

function QueryCRM() {

 var Id = Xrm.Page.data.entity.getId();
 var url = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/LeadSet(guid'" + Id + "')";

 var req = new XMLHttpRequest();

 req.open("GET", url, false);
 req.setRequestHeader("Accept", "application/json");
 req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 req.send();


 if (req.readyState == 4 /* complete */) {
 //Success 
 if (req.status == 200) {
 alert(req.responseText);
 }
 //Failure
 else {
 alert("Error: " + req.responseText);
 }
 }

}

When we run the page we see:

We can also use JSON.parse to parse the results:

JSON.parse(retrieveReq.responseText).d;

If we want to get the value of a field, we can use:

 var res = JSON.parse(req.responseText).d;
 var LastName = res.LastName;
 alert (LastName);

If there are errors, debug using:

debugger;

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *