Hello,
I'm trying to perform a data request via a REST JS code (I used REST Builder, https://github.com/jlattimer/CRMRESTBuilder).
The idea is I am trying to see which competitors are linked to an opportunity, then add all their names into a single string, and then return that value so it's accessible in another function.
The issue is that I can't seem to store/return a global variable that would be accessible outside this function (StringOfCompetitors seen below).
For example, here is my function that I wish to return the string of the competitors:
function StringOfCompetitors(){ var req = new XMLHttpRequest(); req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/opportunities(5817E8E6-CE2C-E611-8120-FC15B428ABA4)?$expand=opportunitycompetitors_association($select=name)", 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.setRequestHeader("Prefer", "odata.include-annotations=\"*\""); req.onreadystatechange = function() { if (this.readyState === 4) { req.onreadystatechange = null; if (this.status === 200) { var result = JSON.parse(this.response); var competitor_string = ""; var opportunityid = result["opportunityid"]; for (var a = 0; a < result.opportunitycompetitors_association.length; a++) { var opportunitycompetitors_association_name = result.opportunitycompetitors_association[a]["name"]; if (a == result.opportunitycompetitors_association.length -1){ competitor_string += result.opportunitycompetitors_association[a]["name"]; } else{ competitor_string += result.opportunitycompetitors_association[a]["name"] + ", "; } } console.log(competitor_string); // correctly gives the string with names of competitors return competitor_string; // ISSUE here, doesn't return anything } else { Xrm.Utility.alertDialog(this.statusText); } } }; req.send(); }
I've tried other variations of when I declare and return the global variable competitor_string and can't seem to get it to work. Is it possible to return a string while doing a REST request? Are there any workarounds?
Thanks!
Edit -xtra details-- The end goal being that I could do this in another function:
var string_comp = StringOfCompetitors();
*This post is locked for comments