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));
Related
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 would like to utilize Xrm.Page.ui.setFormNotification to display a banner at the top of a Shipment record. This banner would only appear for Shipments where the related entity Account is classified as "Service Watch".
I'm pretty new to Javascript so I'm a bit lost how to pull values from related entities of a record to use.
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch", "WARNING")
EDIT: Code working;
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
"/api/data/v8.2/accounts(" + accountid + ")?
$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", 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 result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}
You have to query the Account lookup record on form load to pull the extra attribute which says "Service watch" and show the notification banner if so.
You can refer this community thread & use the sample code as is or Xrm.Webapi method to do it based on your CRM version.
function checkAccount(){
var accountid = Xrm.Page.data.entity.attributes.get("new_parentaccount").getValue()[0].id;
if (accountid.startsWith("{") && accountid.endsWith("}"))
{
accountid = accountid.slice(1, accountid.length - 1);
}
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=new_servicewatch", 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 result = JSON.parse(this.response);
var serviceWatch = result["new_servicewatch"];
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} else
{
//Xrm.Page.ui.clearFormNotification("1");
}
}
else
{
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
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.
Iam new to Phonegap, Iam not able to get the Response while Parsing the XML Url.what i have tried is,
function initLoginPage() {
var xmlhttp = new XMLHttpRequest();
var urlString = "url/app/api.php?fn=employees";
xmlhttp.onreadystatechange = processData;
xmlhttp.open("GET", urlString, true);
xmlhttp.send();
}
function processData() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
} else{document.getElementById().innerHTML = "<b>Please Wait..</b>";}
}
I have called initLoginPage function when device is Ready.I have to show the Response in listView. iam using JQuery Mobile.The Response of Url is
<?xml version="1.0" encoding="UTF-8" ?>
<details>
<responsecode>200</responsecode>
<Employee>
<name>name</name>
<Fathername>fathename</Fathername>
<Address>address</Address>
<Number>12342456</Number>
<Enumber>4324421341234</Enumber>
<OfficeMail>test#gmail.com</OfficeMail>
<PersonalMail>test#gmail.com</PersonalMail>
<EmployeeID>1</EmployeeID>
<DOB>21-06-1991</DOB>
<DOJ>05-03-2013</DOJ>
<PanNumber>123456</PanNumber>
<image>./images/1380372683.png</image>
</Employee>
</details>
Yo have do mistake
var urlString = url+"/app/api.php?fn=employees";
The variable xmlhttp is only defined in the scope of the initLoginPage function, so it isn't defined in processData.
There are two ways to solve your Problem. You use this instead of xmlhttp in processData:
function initLoginPage() {
var xmlhttp = new XMLHttpRequest();
var urlString = "url/app/api.php?fn=employees";
xmlhttp.onreadystatechange = processData;
xmlhttp.open("GET", urlString, true);
xmlhttp.send();
}
function processData() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
else {
document.getElementById().innerHTML = "<b>Please Wait..</b>";}
}
}
Or pass processData as an anonymous function directly to xmlhttp.onreadystatechange:
function initLoginPage() {
var xmlhttp = new XMLHttpRequest();
var urlString = "url/app/api.php?fn=employees";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
else {
document.getElementById().innerHTML = "<b>Please Wait..</b>";}
}
}
xmlhttp.open("GET", urlString, true);
xmlhttp.send();
}
I am trying to retrieve data from json webservice.
if (xmlHttp.status == 200 || xmlHttp.status == 0)
{
var result = xmlHttp.responseText;
json = eval("(" + result + ")");
}
i"m getting nothing for the var result. When i replace the webservice with a text file which contains json object, then i can retrieve the json object as responseText. Please help
First things first... never ever, ever, ever use eval*. eval = evil.
How to use GET with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service?val1=Laura&val2=Linney" + Math.random();
var params = "val1=Laura&val2=Linney";
http.open("GET", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send();
How to use POST with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service";
var params = "val1=Laura&val2=Linney";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send(params);