I am implementing a XMLHTTPRequest
, but am unable to trigger onreadystatechange
function.
May I know how can I troubleshoot it? Thank you.
function DisableDuplicateModuleCreation(context) {
debugger;
var saveEvent = context.getEventArgs();
var user_userid= Xrm.Page.getAttribute("user_userid").getValue();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/modules?$select=user_userid&$filter=user_userid eq '" + user_userid + "' and statecode eq eq", 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=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () { //last stop of this code and jumps to the end without going into function
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
alert("results.entities.length: " + results.entities.length);
if (results.entities.length > 0) {
alert("Module failed to create due to an existing module for User ID " + user_userid + ". Please update the existing module.");
saveEvent.preventDefault();
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
} //jumps to end of code after => req.onreadystatechange = function () from above
You have created var/object req
but you have not send this object,
You are missing req.send();
Here is one sample XMLHttpRequest
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/accounts?$select=address2_county&$filter=accountid eq 1234567899", 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 results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var address2_county = results.value[i]["address2_county"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
If I may go one step furthure and suggest, Try using Xrm.Webapi
to perform webapi request. Microsoft highly recomend using Xrm.Webapi
Note:Xrm.Webapi
is Asynchronous, you might want to use promise to make it work like Sync/or wait for your request to finish
Xrm.WebApi.online.retrieveMultipleRecords("account", "?$select=address2_county&$filter=accountid eq 1234567899").then(
function success(results) {
for (var i = 0; i < results.entities.length; i++) {
var address2_county = results.entities[i]["address2_county"];
}
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);