web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

using REST API with JavaScript

(0) ShareShare
ReportReport
Posted on by 140

I'm new to use REST API with JavaScript for Dynamics CRM, i'm using the CRM Rest Builder to crate the API, would anyone care to share how to use REST API with JavaScript function. any code snippet you use, if i could use as a example, i would greatly appreciate that.

Thanks!

( for example i'm trying to do is get a option-set value from one entity and pass it to different field in another entity ) 

*This post is locked for comments

I have the same question (0)
  • a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Rest Builder provides you a code snippet. What exactly is not clear for you?

  • Community Member Profile Picture
    on at

    Hola. así se consume un servicio

        var serverUrl = Xrm.Page.context.getClientUrl();

    // Obtengo el Guid de la entidad
    var guidCiudad = Xrm.Page.data.entity.getId();

    guidCiudad = guid.replace("{", "");
    guidCiudad = guid.replace("}", "");

            // Consumo el api rest
            var oDataSelect = serverUrl + "/api/data/v8.0/territories?$filter=territoryid eq " + guidCiudad;
    
            var retrieveReq = new XMLHttpRequest();
            retrieveReq.open("GET", oDataSelect, false);
            retrieveReq.setRequestHeader("Accept", "application/json");
            retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    
            retrieveReq.onreadystatechange = function ()
            {
                if (retrieveReq.readyState == 4
                    && retrieveReq.status == 200)
                {
                    var resultado = JSON.parse(retrieveReq.responseText);
                }
            };
    
            retrieveReq.send();
        


  • a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Your code would not work.

    guidCiudad = guid.replace("{", "");

    this line will throw an error that guid is not defined.

  • Kalana1985 Profile Picture
    140 on at

    function optionset1() {
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_test1s()?$select=new_option", true);
    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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var result = JSON.parse(this.response);
    var new_option = result["new_option"];
    var new_option_formatted = result["new_option@OData.Community.Display.V1.FormattedValue"];
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }
    }
    };
    req.send();

    }
    function SetMultiSelValues(executionContext) {
    //get value form multyiselect1
    var formContext = executionContext.getFormContext();

    //Get Array of Selected OptionSet Values
    var selectedValues = formContext.getAttribute("optionset1");
    // setting value

    if (selectedValues != null) {
    formContext.getAttribute("new_option2").setValue(selectedValues);

    } else {
    formContext.getAttribute("new_option2").setValue(" ");
    }
    };

    im just having trouble hoicking API to JS function, any help is greatly appreciated 

  • Community Member Profile Picture
    on at

    hello,

    If you are right, it would be like this.

    guidCiudad = guidCiudad .replace("{", "");

    guidCiudad = guidCiudad .replace("}", "");

    I copied the code lightly and did not realize,

    regards

  • Suggested answer
    Arun Vinoth Profile Picture
    11,615 Moderator on at

    Try to debug the code if you have no clue.

    Add debugger; in your JavaScript & publish the webresource. Then open/refresh the browser & reproduce the steps.

    Breakpoint will hit in debugger; line in browser console, then you can debug line by line like visual studio.

    Errors will be logged in error console as well, also add try catch block as a best practice.

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi kalana,

    Try the be;low code (refactored from your code- basically calling the web pi from the main js method and settign the value after retriing the results- havent tested it but should work)

    ====================

    function SetMultiSelValues(executionContext) {

       //get value form multyiselect1

       var formContext = executionContext.getFormContext();

       var req = new XMLHttpRequest();

       req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_test1s()?$select=new_option", true);

       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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

       req.onreadystatechange = function () {

           if (this.readyState === 4) {

               req.onreadystatechange = null;

               if (this.status === 200) {

                   var result = JSON.parse(this.response);

                   var new_option = result["new_option"];

                   var new_option_formatted = result["new_option@OData.Community.Display.V1.FormattedValue"];

                   if (new_option != null) {

                       formContext.getAttribute("new_option2").setValue(new_option);

                   }

               } else {

                   Xrm.Utility.alertDialog(this.statusText);

               }

           }

       };

       req.send();

    };

    =====================

    If you need to know the basics of CRM javascript then you can refer this- neilparkhurst.com/.../javascript-basics

    Hope this helps.

  • Kalana1985 Profile Picture
    140 on at

    Hello Ravi, i refracted my code as per yours above, and add it ad onLoad event, but unfortunately its not working as expected, ill attached my code below.

    // API retrive for Speialty in credentialing

    function setRevSpecialty(executionContext) {

       var formContext = executionContext.getFormContext();

       var req = new XMLHttpRequest();

       req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/hqi_credentialings()?$select=hqi_specialty", true);

       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.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

       req.onreadystatechange = function () {

           if (this.readyState === 4) {

               req.onreadystatechange = null;

               if (this.status === 200) {

                   var result = JSON.parse(this.response);

                   var hqi_specialty = result["hqi_specialty"];

                   var hqi_specialty_formatted = result["hqi_specialty@OData.Community.Display.V1.FormattedValue"];

                   //checking credentialing specialty value and passing it to hqi_reviewerspecialty1

                   if (hqi_specialty != null) {

                       formContext.getAttribute("hqi_reviewerspecialty1").setValue(hqi_specialty)

                   }

               } else {

                   Xrm.Utility.alertDialog(this.statusText);

               }

           }

       };

       req.send();

    };

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi kalana,

    Did you debug if the value is being returned by the web api? Do you see any error in ui or developer tool?

  • Kalana1985 Profile Picture
    140 on at

    Hello Ravi,

    do i have to provide JSON reassurances to code when using REST API ? one of the Microsoft tech suggest me that.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans