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)

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

I have the same question (0)
  • Suggested answer
    Rawish Kumar Profile Picture
    13,758 on at

    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 :)

  • DianeF1 Profile Picture
    210 on at

    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
    Preeti Sharma Profile Picture
    2,678 on at

    Hi,

    Please try declaring spirit name as below:

    var spirit_name=null;

    Hope it helps:)

  • shaikh sharef Profile Picture
    80 on at

    change the method from Async to Sync.

    var req = new XMLHttpRequest();

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

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

  • Verified answer
    Emre GULCAN Profile Picture
    2,379 on at

    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");
        }
    }


  • Suggested answer
    Jan Gracelin Jeno Profile Picture
    150 on at

    Yup ,Change the Isasync to false.

    The data may not be retrieved.

  • Emre GULCAN Profile Picture
    2,379 on at

    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.

  • DianeF1 Profile Picture
    210 on at

    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?

  • Verified answer
    Emre GULCAN Profile Picture
    2,379 on at

    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);
        }
    });


  • Suggested answer
    shaikh sharef Profile Picture
    80 on at

    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);
    }

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