Search code examples
javascriptdynamics-crmcrmmicrosoft-dynamics

BAD REQUEST When making an AJAX CALL: This.readyState is undefined


I wrote a function that fetches the guid of a lookup field and uses that to make an AJAX call. This is the the call that I made:

fetchOptionSet: function (executionContext) {
        var formContext = executionContext.getFormContext(); //get form context
        var client = Xrm.Page.context.getClientUrl(); //get client url
        var childId = formContext.getAttribute("new_childid").getValue()[0].id;
        var child = childId.replace(/[{}]/g, "");

        var contract;
        var req = new XMLHttpRequest();
        req.open("GET", client + `/api/data/v8.2/new_childallergieses(${child})?$select=_new_childid_value`, 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_childid_value = result["_new_childid_value"];
                    contract = _new_childid_value.replace(/[{}]/g, "");
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();

However, I get a bad request every time that the script runs. I need the guid returned by the call (contractid) to make another ajax call! The uri is fine,I tested the link in the browser and it returns the contractid that I want.

Debug


Solution

  • Changed from Asychronous to Sychronous and all of a sudden it worked!

     var path_one = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_childallergieses(" + child + ")?$select=_new_childid_value";
     req.open("GET", path_one , false);

    I did some investigating and realized that the function is set to execute on load, and sending an asynchronous call on load gives a bad request.