Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Accessing data retrieved via XMLHttpRequest

(0) ShareShare
ReportReport
Posted on by 210

Hi Experts,

I'm new to WebAPI and javascript (my life has been .Net until now) so I know this is probably a basic question.

My requirement is to query an entity and use that information further in my javascript.  I'm having troubles getting the queried data out of the function so that I can use it.  My alert from within the function in the onreadystatechange shows that the data was retrieved.  My alert that is after the req.send throws an error.  How do I get the data outside of that "inner" function so that I can be used by other processes?

Diane

function getContractChange(ccId) {
    ccId = "67457cab-aab9-e711-80ea-0050569b0dd7";
    var spirit_name
    var ccServices = null;
    var queryPath = "/api/data/v8.2/spirit_changecontracts(67457cab-aab9-e711-80ea-0050569b0dd7)" +
        "?$select=spirit_changecontractnumber,_spirit_contract_value,spirit_contractchangenumber,spirit_generaltypeofchange,spirit_name";
    var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
    alert(requestPath);

    var req = new XMLHttpRequest();
    
    req.open("GET", requestPath, 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.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var result = JSON.parse(this.response);
                spirit_name = result["spirit_name"];
                alert("inside " + spirit_name);
            }
            else {
                alert(this.statusText);
            }
        }
    };    
    req.send();
    alert("name is" + spirit_name);
}

*This post is locked for comments

  • Suggested answer
    shaikh sharef Profile Picture
    shaikh sharef 80 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Dianef1,

    You can use a global varibale to use your data outside a function, see red color code.

    var result ;

    var spirit_name ;

    function getContractChange(ccId) {
        ccId = "67457cab-aab9-e711-80ea-0050569b0dd7";
        var spirit_name
        var ccServices = null;
        var queryPath = "/api/data/v8.2/spirit_changecontracts(67457cab-aab9-e711-80ea-0050569b0dd7)" +
            "?$select=spirit_changecontractnumber,_spirit_contract_value,spirit_contractchangenumber,spirit_generaltypeofchange,spirit_name";
        var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
        alert(requestPath);
    
        var req = new XMLHttpRequest();
        
        req.open("GET", requestPath, 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.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                     result = JSON.parse(this.response);
                    spirit_name = result["spirit_name"];
                    alert("inside " + spirit_name);
                }
                else {
                    alert(this.statusText);
                }
            }
        };    
        req.send();
        alert("name is" + spirit_name);
    }
  • Verified answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    If you select "output format" to "jQuery", you need add jQuery codes to your form.

    Download jQuery source code from http://jquery.com/download/ and add as a "webresource" to your Dynamics CRM, after that add / reference as library to your form (be aware of library "ordering", jQuery library should be first order and your other libraries should be after that reference to jQuery )

    3465.05.png

    Your jQuery request code like below, be aware "async" property, Jquery Ajax's "async" property default value is "true" and don't need to add to your code, if you set this false works as sync

    var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(A076D3A1-12F9-E711-A94F-000D3AB50338)?$select=accountid,accountnumber";
    
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: apiUrl,
        beforeSend: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
            XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        },
        async: true,
        success: function(data, textStatus, xhr) {
            var result = data;
            var accountid = result["accountid"];
            var accountnumber = result["accountnumber"];
        },
        error: function(xhr, textStatus, errorThrown) {
            Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
        }
    });


  • DianeF1 Profile Picture
    DianeF1 210 on at
    RE: Accessing data retrieved via XMLHttpRequest

    When I used the REST builder (which was awesome BTW).  I was getting an error stating that $ in "$.ajax({..." was undefined.  What other libraries should be included?

  • Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Jan,

    I'm mostly using SYNC requests and I don't have any problem about retrieving data from MS CRM.

    Sync / async structure is about your business logic / requirements.

  • Suggested answer
    Jan Gracelin Jeno Profile Picture
    Jan Gracelin Jeno 150 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Yup ,Change the Isasync to false.

    The data may not be retrieved.

  • Verified answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    When using async request you can't return your data directly, you should use "callback" function. Please look at this code example with Sync and Async methods (and be aware for red code lines)

    If your Dynamics CRM version is 365 (v9) you can also use Xrm.WebApi functions to use D365 webapi (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-webapi), however this methods use Async request, so you need callback or directly code inside this methods.

    You can use CRM REST Builder solution (https://github.com/jlattimer/CRMRESTBuilder) to create your request.

    var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(A076D3A1-12F9-E711-A94F-000D3AB50338)?$select=accountid,accountnumber";
    
    function mainMethod() {
        alternate1_sync(); //do your business inside "req.onreadystatechange"
        alternate2_async_with_callback(); //do your business inside callback function "myAsyncCallbackMethod"
    
        /*
        If "isAsync" parameter is false, XMLHttpRequest running Synchronous and you can get your data out of your function (with return),
        otherwise (when Asynchronous process) you should do your business inside "req.onreadystatechange" or use "callback" function inside "req.onreadystatechange" to get data out.
     */
    }
    
    function alternate1_sync() {
        var isAsync = false;
        var data = null;
    
        var req = new XMLHttpRequest();
        req.open("GET", apiUrl, isAsync);
        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);
                    data = result;
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    
        return data;
    }
    
    function alternate2_async_with_callback() {
        var isAsync = true;
    
        var req = new XMLHttpRequest();
        req.open("GET", apiUrl, isAsync);
        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);
                    myAsyncCallbackMethod(result);
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }
    
    function myAsyncCallbackMethod(data) {
        //you should do your business inside this method
        //for example
    
        var accountid = data["accountid"];
        var accountnumber = data["accountnumber"];
    
        if (accountnumber == "123") {
            alert("Hello world");
        }
    }


  • shaikh sharef Profile Picture
    shaikh sharef 80 on at
    RE: Accessing data retrieved via XMLHttpRequest

    change the method from Async to Sync.

    var req = new XMLHttpRequest();

       req.open("GET", requestPath, false);

       req.setRequestHeader("OData-MaxVersion", "4.0");

  • Suggested answer
    Preeti Sharma Profile Picture
    Preeti Sharma 2,678 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    Please try declaring spirit name as below:

    var spirit_name=null;

    Hope it helps:)

  • DianeF1 Profile Picture
    DianeF1 210 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Here's the issue.  As long as I'm in the "req.onreadystatechange = function" I can access those items from result.  But once I am past the req.send any of those fields an error is thrown. The "alert("name is" + spirit_name);" states that spirit_name is undefined. I did the var spirit_name at the top of the original code and outside of readystatechange.  How do I get the data outside of readystate function?

  • Suggested answer
    Rawish Kumar Profile Picture
    Rawish Kumar 13,756 on at
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Diane,

    you will get everything that you have retrieved in "result".

    i see that you have retrieved couple field from spirit_changecontracts entity

    so it would be like :

    var new = result["spirit_changecontractnumber"];

    var new 1 = result["spirit_contractchangenumber"];

    etc

    so whatever fields that you have "select" in the query - you can retrieve them and use anywhere.

    I hope i have answered your question - if not , please correct me :)

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

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Congratulations to the January Top 10 leaders!

Check out the January community rock stars...

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,996 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 230,853 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans