JimmyCromulent
JimmyCromulent

Reputation: 1

Dynamics CRM 2016: JavaScript causes JSON Parse Error

I am trying to get the price of a product in Dynamics CRM 2016, by javascript on the onChange event for the product. This is on a custom entity I have created and is using the pricelistid and the productid.

When I use the same javascript in the console on Chrome i can get the data out but when it is executed by the CRM form I get an error:

SyntaxError: Unexpected end of JSON input at JSON.parse ()

The code is:

var pricelevelid = Xrm.Page.getAttribute("sg_pricelistid").getValue()[0].id;
pricelevelid = pricelevelid.replace(/[{}]/g, "");

var productdata = Xrm.Page.getAttribute("sg_productid").getValue();
if (productdata != null)
        {
        console.log("going into productdata loop");
        productid = productdata[0].id;
        productid = productid.replace(/[{}]/g, "");

        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/productpricelevels?$select=amount,_pricelevelid_value,_productid_value,productpricelevelid&$filter=_pricelevelid_value eq " + pricelevelid + " and  _productid_value eq " + productid + "", 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 results = JSON.parse(this.response);
                        for (var i = 0; i < results.value.length; i++) {
                            var amount = results.value[i]["amount"];
                            var amount_formatted = results.value[i]["[email protected]"];
                        }
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();

        data = JSON.parse(req.responseText);
        var amount = data.value[0]["amount"];
        Xrm.Page.getAttribute("sg_unitprice").setValue(amount);
        }

Upvotes: 0

Views: 1277

Answers (1)

mktange
mktange

Reputation: 417

You are performing an asynchronous request and then attempting to parse the response, before it has been set to anything.

This happens at the bottom of your code block at data = JSON.parse(req.responseText), right after you send the request.

All code that relies on the response should be executed in the req.onreadystatechange callback function.

Upvotes: 2

Related Questions