How to make an OData request from JavaScript Web Resource to Dynamics API

Sometimes the task you are trying to accomplish cannot be done using the supplied toolset by Microsoft via the development graphical interface, we can accomplish anything you can imagine with some fields and some code.

If there’s some info that is not accessible from the form’s context, which is very useful when creating custom field logic, you can use an OData request which uses the provided developer gateway that dynamics provides.

In order to use this gateway I will leave this code snippet here in case anyone finds it useful, and I can save you some valuable development time:

    // get the userId to construct the Query URL.
    var userId = Xrm.Utility.getGlobalContext().userSettings.userId;
    // remove { and } from the userId
    userId = userId.replace("{", "").replace("}", "");

    //Making the Request
    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/systemusers("+userId+")?$select=_businessunitid_value", false);
    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);
                ****YOUR LOGIC
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();

Happy Customizations!