Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Return a value after running a REST/XMLHttpRequest request

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

  • HodgesW Profile Picture
    HodgesW 410 on at
    RE: Return a value after running a REST/XMLHttpRequest request

    [quote user="Saad Akhtar"]

    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

    community.dynamics.com/.../ms-dynamics-crm-login-user-39-s-security-role-using-javascript

    [/quote]

    After referring to some other stackoverflow questions, it looks like will probably have to use a jquery/ajax call using the 'success' feature (as shown in your link) and possibly the a 'Promise' api.

    https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Return a value after running a REST/XMLHttpRequest request

    When are you going to mark my answer? LOL

    Are you still struggling for anything?

  • HodgesW Profile Picture
    HodgesW 410 on at
    RE: Return a value after running a REST/XMLHttpRequest request

    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.

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Return a value after running a REST/XMLHttpRequest request

    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

  • Nithya Gopinath Profile Picture
    Nithya Gopinath 17,074 on at
    RE: Return a value after running a REST/XMLHttpRequest request

    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
    HodgesW Profile Picture
    HodgesW 410 on at
    RE: Return a value after running a REST/XMLHttpRequest request

    [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.

  • HodgesW Profile Picture
    HodgesW 410 on at
    RE: Return a value after running a REST/XMLHttpRequest request

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

  • Verified answer
    Wauters Profile Picture
    Wauters 90 on at
    RE: Return a value after running a REST/XMLHttpRequest request

    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

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Return a value after running a REST/XMLHttpRequest request

    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;

    }

  • a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Return a value after running a REST/XMLHttpRequest request

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

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans