I am currently trying to run 2 separate XMLHTTPRequests in dynamics CRM Javascript to retrieve data from 2 different entities and run code depending on what is retrieved..
I've done my best to try and edit some names for security reasons, but the premise is the same.
My main problem is that the first run of the XMLHTTPRequest (the RA Banner) works fine, but then the second run (the Status Banner) the Readystate that is returned is 2 and stopping.
function FormBanners(formContext) {
//Clear the existing banners
formContext.ui.clearFormNotification("Notif1");
formContext.ui.clearFormNotification("Notif2");
//Get the customer/rep
var customer = formContext.getAttribute("customerid").getValue();
var rep = formContext.getAttribute("representative").getValue();
var contact;
//use the rep if there is one else use the customer
if (rep != null) {
contact = rep;
}
else if (customer!= null) {
contact = customer;
}
//Get the account
var account = formContext.getAttribute("accountfield").getValue();
//As there is a requirement for 2 XMLHTTPRequests we have to queue them
var requestURLs = new Array();
//There will always be a customers or rep on the form
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/contacts?$select=new_RA,new_SC,new_VC,new_PR&$filter=contactid eq " + contact[0].id + "", true);
//there may not be an account
if (account) {
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?$select=_new_statusLookup_value&$filter=accountid eq " + account[0].id + "", true);
}
var current = 0;
function getURL(url) {
var req = new XMLHttpRequest();
req.open("GET", requestURLs[current]);
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(req.response);
// Creation of the RA Banner
if (current == 0) {
var RA = result.value[0]["new_RA#OData.Community.Display.V1.FormattedValue"];
var SC = result.value[0]["new_SC#OData.Community.Display.V1.FormattedValue"];
var VC = result.value[0]["new_VC#OData.Community.Display.V1.FormattedValue"];
var PR = result.value[0]["new_PR#OData.Community.Display.V1.FormattedValue"];
var Notif = "";
//Only create a notification if any of the above contain "Yes"
if (RA == "Yes" || SC == "Yes" || VC == "Yes" || PR == "Yes") { Notif = "The Customer/Rep has:" }
if (RA == "Yes") { Notif = Notif + " RA,"; }
if (SC == "Yes") { Notif = Notif + " SC,"}
if (VC == "Yes") { Notif = Notif + " VC,"}
if (PR == "Yes") { Notif = Notif + " PR."}
if (Notif != "") {
formContext.ui.setFormNotification(Notif, "INFO", "Notif1");
}
}
//Creation of the Status Banner
else if (current == 1) {
status = results.value[i]["_new_statusLookup_value"];
if (status) {
if (status[0].name != "Open")
var Notif = "The status for the organisation on this case is " + status[0].name + ".";
formContext.ui.setFormNotification(Notif, "INFO", "Notif2");
}
}
++current;
if (current < requestURLs.length) {
getURL(requestURLs[current]);
}
} else {
Xrm.Utility.alertDialog(req.statusText);
}
}
}; req.send();
}
getURL(requestURLs[current]);
}
Can anyone help me out?
So in my example I had made many mistakes. Taking Arun's advice I separated the function out, which made debugging far easier.. it instead was not failing on the XMLHTTP Request because that worked fine, but firefox was crashing when debugging.
So my issues were that I was in the second part:
Used the value of i for results (i was no longer defined)
Getting the "_new_statusLookup_value" would only provide the guid of the lookup I would instead want "_new_statusLookup_value#OData.Community.Display.V1.FormattedValue"
Lets not ignore the fact that because I had copied and pasted many iterations of this code that I was also using "results" instead of "result".
Many little mistakes.. but it happens! Thanks for the help, just goes to show.. typos are our downfall!
Posting this because I found a lot of jquery answers, but no raw javascript answers.
So I have a function to post a comment to a comment section, and I want the comment section to refresh after posting a comment, But for some reason my code isn't working.
The code for loading the comment section:
function loadCommentSection() {
console.log("loading section")
imgid = imgid.replace("img/pic (", "");
imgid = imgid.replace(").jpg", "");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("commentsection").innerHTML = this.responseText;
}
};
xhttp.open("GET", "commentsection.php?imgid=" + imgid, true);
xhttp.send();
}
and the code for submitting the comment:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
loadCommentSection();
}
The problem is that the loadCommentSection function in the submitComment function isn't executing.
You should allow the comment to be sent to the server and be registered before calling loadCommentSection. So, it is probably best to call it when the response becomes available:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
loadCommentSection(); // <<---- moved here.
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
}
What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();
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>