I am trying to discern if a user is a member of a certain team in Dynamics 365. I am using the following JavaScript functions to attempt this. My issue is that even though the getUserTeams is finding the user in the team when the result gets passed back to the calling function (UserHasTeam) the value is undefined. I feel like I am missing something here but for the life of me I don't know what. Can anyone help me?
function UserHasTeam(teamName) {
///<summary>
/// Checks to see if the current user is a member of a team with the passed in name.
///</summary>
///<param name="teamName" type="String">
/// A String representing the name of the team to check if the user is a member of.
///</param>
var res;
if (teamName != null && teamName != "") {
// build endpoint URL
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
// query to get the teams that match the name
oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
console.log(oDataEndpointUrl);
// execute the request
var req = new XMLHttpRequest();
req.open("GET", oDataEndpointUrl, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
console.log("Success");
result = JSON.parse(this.response);
console.log(result);
console.log(result["d"]["results"][0]["TeamId"]);
res = getUserTeams(result["d"]["results"][0]["TeamId"]);
console.log(res);
} else {
var error = JSON.parse(this.response).error;
console.log(error);
}
}
};
req.send(null);
return res;
}
}
function getUserTeams(teamToCheckId) {
// gets the current users team membership
var res;
var userId = Xrm.Page.context.getUserId().substr(1, 36);
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
oDataEndpointUrl += "TeamMembershipSet?$filter=SystemUserId eq guid' " + userId + " ' and TeamId eq guid' " + teamToCheckId + " '";
var req = new XMLHttpRequest();
req.open("GET", oDataEndpointUrl, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
console.log("Success");
result = JSON.parse(this.response);
console.log(result["d"]["results"].length);
if(result["d"]["results"].length == 1) {
res = true;
} else {
res = false;
}
} else {
var error = JSON.parse(this.response).error;
console.log(error);
}
}
};
req.send(null);
return res;
}
you are calling webapi request as Async and not sync.
req.open("GET", oDataEndpointUrl, true);
You should be calling it Sync like below
req.open("GET", oDataEndpointUrl, false);
In addition, if you are using Dynamics 365 you should be using up to date webapi request.
Note: new webapi calls are in build Async and you should be using promise to make it sync.
Take a look at this retrievemultiplerecords
and retrieveRecord
Please mark it as solved if it helps
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]["amount#OData.Community.Display.V1.FormattedValue"];
}
} 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);
}
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.
I am trying to associate two records of custom entities - 'Custom entity 1' and 'Custome Entity 2' having N:N relationship on MS CRM 2016 online instance using Web API. I am getting the following error alert -
An unexpected ‘StartArray’ node was found when reading from the JSON reader. A ‘StartObject’ node was expected.
Following is the code snippet -
function associateRequest() {
var serverURL = Xrm.Page.context.getClientUrl();
var associate = {
"#odata.id": serverURL + "/api/data/v8.0/new_customentity1s(08C7365D-4BD1-E511-80EA-3863BB34BA88)"
};
var req = new XMLHttpRequest();
req.open("POST", serverURL + "/api/data/v8.0/new_customeentity2s(9A1EF77F-4BD1-E511-80EA-3863BB34BA88)/new_new_customentity1_new_customeentity2/$ref", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 204) {
alert('Record Associated');
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(associate);
}
The disassociation of the records is working fine.
I think you need to use JSON.stringify on the object you're posting:
var association = {'#odata.id': Xrm.Page.context.getClientUrl() + "/api/data/v8.0/new_tests(37A8B2B7-73C9-E511-80DE-6C3BE5A8DAD0)"};
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/new_test2s(9002CEE2-E9D3-E511-80DD-6C3BE5BD3F5C)/new_new_test_new_test2/$ref", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204 || this.status === 1223) {
//Success - No Return Data - Do Something
}
else {
alert(this.statusText);
}
}
};
req.send(JSON.stringify(association));
I have the following code that grabs all the data from an array and then displays it in a certain div within an HTML document. Right now the data is embedded into the code, yet I need to grab this same data from a URL. As you can see I already started the XHR request & tested it's retrieval successfully. I'm just not sure once the data is grabbed from the URL how to display it within the HTML similarly as it works now?
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
// LOAD AND DISPLAY LOCATION DATA
window.onload=function(){
var data = [
{"id":1271832,"segment_id":3345,"latitude":37.7029,"longitude":-121.9335,"name":"Verve","address_1":"7886 Dublin Blvd","phone_number":"555-324-5678","postal_code":"94568","postal_code_id":"7168","metro":"San Francisco-Oakland-San Jose CA","city":"Dublin","region":"CA","country":"US","m":4934,"km":4.9,"miles":3.07},
{"id":1271836,"segment_id":3345,"latitude":37.6958,"longitude":-121.9255,"name":"Verve","address_1":"1 Stoneridge Mall Space","phone_number":"555-324-5678","postal_code":"94588","postal_code_id":"7169","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasanton","region":"CA","country":"US","m":5045,"km":5,"miles":3.14},
{"id":1271831,"segment_id":3345,"latitude":37.6931,"longitude":-121.9262,"name":"Verve","address_1":"1120 Stoneridge Mall Drive","phone_number":"555-324-5678","postal_code":"94566","postal_code_id":"7167","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasanton","region":"CA","country":"US","m":5325,"km":5.3,"miles":3.31},
{"id":1271827,"segment_id":3345,"latitude":37.6999,"longitude":-121.7452,"name":"Verve","address_1":"4408 Las Positas Rd","phone_number":"555-324-5678","postal_code":"94551","postal_code_id":"7138","metro":"San Francisco-Oakland-San Jose CA","city":"Livermore","region":"CA","country":"US","m":13375,"km":13.4,"miles":8.31},
{"id":1271826,"segment_id":3345,"latitude":37.6966,"longitude":-122.0771,"name":"Verve","address_1":"3450 Village Dr","phone_number":"555-324-5678","postal_code":"94546","postal_code_id":"7133","metro":"San Francisco-Oakland-San Jose CA","city":"Castro Valley","region":"CA","country":"US","m":16796,"km":16.8,"miles":10.44},
{"id":1271838,"segment_id":3345,"latitude":37.8948,"longitude":-122.0591,"name":"Verve","address_1":"1295 S Main St","phone_number":"555-324-5678","postal_code":"94596","postal_code_id":"7292","metro":"San Francisco-Oakland-San Jose CA","city":"Walnut Creek","region":"CA","country":"US","m":23294,"km":23.3,"miles":14.48},
{"id":1271833,"segment_id":3345,"latitude":37.7114,"longitude":-122.1638,"name":"Verve","address_1":"1285 Marina Boulevard","phone_number":"555-324-5678","postal_code":"94577","postal_code_id":"7170","metro":"San Francisco-Oakland-San Jose CA","city":"San Leandro","region":"CA","country":"US","m":24055,"km":24.1,"miles":14.95},
{"id":1271819,"segment_id":3345,"latitude":37.9499,"longitude":-121.9603,"name":"Verve","address_1":"5412 Ygnacio Valley Rd","phone_number":"555-324-5678","postal_code":"94521","postal_code_id":"7254","metro":"San Francisco-Oakland-San Jose CA","city":"Concord","region":"CA","country":"US","m":24926,"km":24.9,"miles":15.49},
{"id":1271817,"segment_id":3345,"latitude":37.9435,"longitude":-121.7376,"name":"Verve","address_1":"2520 Sand Creek Rd","phone_number":"555-324-5678","postal_code":"94513","postal_code_id":"7248","metro":"San Francisco-Oakland-San Jose CA","city":"Brentwood","region":"CA","country":"US","m":27090,"km":27.1,"miles":16.84},
{"id":1271820,"segment_id":3345,"latitude":37.9452,"longitude":-122.0627,"name":"Verve","address_1":"157 Crescent Plaza","phone_number":"555-324-5678","postal_code":"94523","postal_code_id":"7256","metro":"San Francisco-Oakland-San Jose CA","city":"Pleasant Hill","region":"CA","country":"US","m":28030,"km":28,"miles":17.42}
];
data.forEach(function (item) {
pios(item)
})
function pios(item) {
var p = document.createElement('p');
p.id = item.id;
p.innerHTML = item.address_1 + '<br>' + item.city + item.region + item.postal_code;
document.getElementById('locations').appendChild(p)
}
}
<div id="locations"></div>
You need to add the onreadystatechange to your xhr:
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
data.forEach(function (item) {
pios(item);
});
}
}
xhr.open("GET", url, true);
xhr.send();
This includes the full methods you provided and linked it into the onload.
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
data.forEach(function (item) {
pios(item);
});
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
};
function pios(item) {
var p = document.createElement('p');
p.id = item.id;
p.innerHTML = item.address_1 + '<br>' + item.city + item.region + item.postal_code;
document.getElementById('locations').appendChild(p)
}
Figured this out and wanted to share. Thanks for the help!
***Don't forget to change http://example.com with the URL to your JSON data.
function getData(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send();
}
function renderData(data) {
console.log(data);
var html = data.pois.slice(0,3).reduce(function (frag, item) {
frag.appendChild(pios(item));
return frag;
}, document.createDocumentFragment());
document.getElementById('locations').appendChild(html);
}
function pios(item) {
var p = document.createElement('pre');
p.id = item.id;
p.textContent = item.address_1 + '\n' + item.city + ' ' + item.region + ' ' + item.postal_code;
return p;
}
getData(renderData);
<div id="locations"></div>