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)

Can not get return value from XMLHttpRequest

(0) ShareShare
ReportReport
Posted on by 458

Hi there All experts.
I have a JS Question.
I have a method in which I get State Code of SalesOrder entity.
Here is what I do :

function returnStateOfOrder() {
    
    var orderStatusReasonId = Xrm.Page.getAttribute("xxxxxx").getValue()[0].id;
    var trimedOrderStatusReasonId = orderStatusReason.replace('{', '').replace('}', '');
    var stateCode;
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/SalesOrderSet(guid'" + trimedOrderStatusReasonId+ "')?$select=StateCode", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            this.onreadystatechange = null;
            if (this.status === 200) {
                var result = JSON.parse(this.responseText).d;
                stateCode = result.StateCode.Value;
                console.log("State code is : " + stateCode);
                console.log(typeof(stateCode));
            } else {
                alert(this.statusText);
                stateCode=-1;
            }
            
        }
        return stateCode;
    };
    req.send();
}

It works Great,In the console It writes the state-code and type of it.
But in Another function that  I call this method and assign the return value in this way :

    switchCaseStateCode=returnStateOfOrder();
    console.log(switchCaseStateCode);




But it display Undefined in the console !
I even changed the Asynchronous to false, But no success !

*This post is locked for comments

I have the same question (0)
  • David Jennaway Profile Picture
    14,065 on at

    This is because the call is asynchronous. This means that the code in the onreadystatechange function only runs after you get a response, whereas your the following line of code is synchronous, so executes immediately (i.e. before a response)

    return stateCode;


    Instead of trying to pass a return value, the normal pattern is for the onreadystatechange function to read the result, and write it to a persistent place (e.g. a form field value)

  • Verified answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Albert ,

    It will always best practice to write  logic inside the success method as most browser does not support synchronous operation due to performance. 

    In addition just give a try with this  -

            function  returnStateOfOrder() {
                var orderStatusReasonId = Xrm.Page.getAttribute("xxxxxx").getValue()[0].id;
                var trimedOrderStatusReasonId = orderStatusReason.replace('{', '').replace('}', '');
                var stateCode;
    
                var serverUrl = Xrm.Page.context.getServerUrl();
                var ODATA_ENDPOINT = "/xrmservices/2011/OrganizationData.svc/";
                var odataSetName = "SalesOrderSet";
                var selectQuery = "?$select=StateCode&$filter=SalesOrderId eq guid'" + orderStatusReasonId + "'"; // Please make sure id name is correct
    
                $.support.cors = true;
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    datatype: "json",
                    url: serverUrl + ODATA_ENDPOINT + odataSetName + selectQuery,
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    success: function (data, textStatus, XmlHttpRequest) {
                        if (data != null && data.d != null && data.d.results != null && data.d.results.length > 0) {
                            stateCode =  data.d.results[0].StateCode.Value;
                            console.log("State code is : " + stateCode);
                            console.log(typeof(stateCode));
                        }
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        console.log("error");
                    }
                });
                return stateCode;
            }


  • Albert_ Profile Picture
    458 on at

    Your code solved that.

    Thank you.

    Im gonna ask another question.

    Could you take a look at that?

    I would insert the link here.

  • Albert_ Profile Picture
    458 on at

    Hi there sir,Could you take a look at this thread?

    Thanks alot.

    community.dynamics.com/.../293115

  • gdas Profile Picture
    50,091 Moderator on at

    Hi Albert ,

    Glad to hear your problem has been resolved. Let me check above thread.

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