web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Return a value after running a REST/XMLHttpRequest request

(0) ShareShare
ReportReport
Posted on by 410

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

I have the same question (0)
  • HodgesW Profile Picture
    410 on at

    Current workaround that isn't ideal, but does the job -- I created a new hidden field "text_transfer" on the form. My  StringOfCompetitors() function will set this field to my list of competitors string (where I have the console.log in the original funciton). Function ends.

    Run other function and know to look at "text_transfer" after running StringOfCompetitors(). If it has a value, grab the text from the field and then clear it. --I didn't want to have to save the form again.

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at

    If your reply answers your question feel free to get back to this thread to close it marking your reply as answer.

  • Verified answer
    Community Member Profile Picture
    on at

    You can change the method from Async to Sync.

    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)", 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.send();

    if (req.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"] + ", ";
    }

    }

    else //when status is not 200

    {

    //do something for error

    }

    return competitor_string;

    }

  • Verified answer
    Wauters Profile Picture
    90 on at

    You'll have to extend your StringOfCompetitors method to accept a callback function as parameter and tie it to the onreadystatechange of the request.

    Getting started with callbacks: closebrace.com/.../understanding-javascript-callbacks

  • HodgesW Profile Picture
    410 on at

    Thanks everyone, will look into the two responses above and see what works for me. Will come back and mark answer

  • Verified answer
    HodgesW Profile Picture
    410 on at

    [quote user="melvin fong"]

    You can change the method from Async to Sync.

    Supposedly 'synchronous requests' are discouraged as they freeze the page while waiting. This isn't a big deal for me because it should run relatively fast (at least it did in my test) and I also plan to show a 'Loading' alert that freezes the page during my method anyways as our users often get confused in CRM whether or not they should wait or click on something.

    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)", 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.send();

    if (req.status == 200){

    var result = JSON.parse(thisreq.response); //received an syntax error while using 'this' but using the 'req' variable works.

    ...}

    rest of code still works & returns the string correctly. See above reply for full code

    [/quote]

    See quote for my comments & one fix.

    I am going to continue to look into properly using a callback function, but this way above does work.

  • Nithya Gopinath Profile Picture
    17,078 on at

    Hi Hodges,

    In order to return the string, you could try the code below.

    function StringOfCompetitors(){
            var competitor_string = "";
    	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 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
    			} else {
    				Xrm.Utility.alertDialog(this.statusText);
    			}
    		}
    	};
    	req.send();
            return competitor_string;
    }

    Hope this helps.

  • Verified answer
    Community Member Profile Picture
    on at

    I don't think we can use return when using web API.

    Refer this:

    lakshmanindian.wordpress.com/.../check-user-security-role-in-crm-2011-using-jscript

    https://community.dynamics.com/crm/b/microsoftdynamicscrmxrm/archive/2014/05/15/ms-dynamics-crm-login-user-39-s-security-role-using-javascript

  • HodgesW Profile Picture
    410 on at

    Nithya -- tried that one before and it actually does not work. It returns "" from when it's declared outside of the request and is not updated to the correct string. I believe this is due to the async nature of the request.

  • Community Member Profile Picture
    on at

    When are you going to mark my answer? LOL

    Are you still struggling for anything?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans