Skip to main content
Post a question

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id : s+xiIMGONkQrpYxz+Z+fi+
Microsoft Dynamics CRM (Archived)

Accessing data retrieved via XMLHttpRequest

Like (0) ShareShare
ReportReport
Posted on 31 Jan 2018 19:46:03 by 210

Hi Experts,

I'm new to WebAPI and javascript (my life has been .Net until now) so I know this is probably a basic question.

My requirement is to query an entity and use that information further in my javascript.  I'm having troubles getting the queried data out of the function so that I can use it.  My alert from within the function in the onreadystatechange shows that the data was retrieved.  My alert that is after the req.send throws an error.  How do I get the data outside of that "inner" function so that I can be used by other processes?

Diane

  1. function getContractChange(ccId) {
  2. ccId = "67457cab-aab9-e711-80ea-0050569b0dd7";
  3. var spirit_name
  4. var ccServices = null;
  5. var queryPath = "/api/data/v8.2/spirit_changecontracts(67457cab-aab9-e711-80ea-0050569b0dd7)" +
  6. "?$select=spirit_changecontractnumber,_spirit_contract_value,spirit_contractchangenumber,spirit_generaltypeofchange,spirit_name";
  7. var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
  8. alert(requestPath);
  9.  
  10. var req = new XMLHttpRequest();
  11. req.open("GET", requestPath, true);
  12. req.setRequestHeader("OData-MaxVersion", "4.0");
  13. req.setRequestHeader("OData-Version", "4.0");
  14. req.setRequestHeader("Accept", "application/json");
  15. req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  16.  
  17. req.onreadystatechange = function () {
  18. if (this.readyState === 4) {
  19. req.onreadystatechange = null;
  20. if (this.status === 200) {
  21. var result = JSON.parse(this.response);
  22. spirit_name = result["spirit_name"];
  23. alert("inside " + spirit_name);
  24. }
  25. else {
  26. alert(this.statusText);
  27. }
  28. }
  29. };
  30. req.send();
  31. alert("name is" + spirit_name);
  32. }

*This post is locked for comments

  • Suggested answer
    shaikh sharef Profile Picture
    shaikh sharef 80 on 05 Feb 2018 at 05:56:24
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Dianef1,

    You can use a global varibale to use your data outside a function, see red color code.

    var result ;

    var spirit_name ;

    1. function getContractChange(ccId) {
    2. ccId = "67457cab-aab9-e711-80ea-0050569b0dd7";
    3. var spirit_name
    4. var ccServices = null;
    5. var queryPath = "/api/data/v8.2/spirit_changecontracts(67457cab-aab9-e711-80ea-0050569b0dd7)" +
    6. "?$select=spirit_changecontractnumber,_spirit_contract_value,spirit_contractchangenumber,spirit_generaltypeofchange,spirit_name";
    7. var requestPath = Xrm.Page.context.getClientUrl() + queryPath;
    8. alert(requestPath);
    9.  
    10. var req = new XMLHttpRequest();
    11. req.open("GET", requestPath, true);
    12. req.setRequestHeader("OData-MaxVersion", "4.0");
    13. req.setRequestHeader("OData-Version", "4.0");
    14. req.setRequestHeader("Accept", "application/json");
    15. req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    16.  
    17. req.onreadystatechange = function () {
    18. if (this.readyState === 4) {
    19. req.onreadystatechange = null;
    20. if (this.status === 200) {
    21. result = JSON.parse(this.response);
    22. spirit_name = result["spirit_name"];
    23. alert("inside " + spirit_name);
    24. }
    25. else {
    26. alert(this.statusText);
    27. }
    28. }
    29. };
    30. req.send();
    31. alert("name is" + spirit_name);
    32. }
  • Verified answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on 01 Feb 2018 at 12:43:19
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    If you select "output format" to "jQuery", you need add jQuery codes to your form.

    Download jQuery source code from http://jquery.com/download/ and add as a "webresource" to your Dynamics CRM, after that add / reference as library to your form (be aware of library "ordering", jQuery library should be first order and your other libraries should be after that reference to jQuery )

    3465.05.png

    Your jQuery request code like below, be aware "async" property, Jquery Ajax's "async" property default value is "true" and don't need to add to your code, if you set this false works as sync

    1. var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(A076D3A1-12F9-E711-A94F-000D3AB50338)?$select=accountid,accountnumber";
    2.  
    3. $.ajax({
    4. type: "GET",
    5. contentType: "application/json; charset=utf-8",
    6. datatype: "json",
    7. url: apiUrl,
    8. beforeSend: function(XMLHttpRequest) {
    9. XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
    10. XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
    11. XMLHttpRequest.setRequestHeader("Accept", "application/json");
    12. XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    13. },
    14. async: true,
    15. success: function(data, textStatus, xhr) {
    16. var result = data;
    17. var accountid = result["accountid"];
    18. var accountnumber = result["accountnumber"];
    19. },
    20. error: function(xhr, textStatus, errorThrown) {
    21. Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
    22. }
    23. });


  • DianeF1 Profile Picture
    DianeF1 210 on 01 Feb 2018 at 12:12:03
    RE: Accessing data retrieved via XMLHttpRequest

    When I used the REST builder (which was awesome BTW).  I was getting an error stating that $ in "$.ajax({..." was undefined.  What other libraries should be included?

  • Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on 01 Feb 2018 at 11:28:00
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Jan,

    I'm mostly using SYNC requests and I don't have any problem about retrieving data from MS CRM.

    Sync / async structure is about your business logic / requirements.

  • Suggested answer
    Jan Gracelin Jeno Profile Picture
    Jan Gracelin Jeno 150 on 01 Feb 2018 at 11:09:42
    RE: Accessing data retrieved via XMLHttpRequest

    Yup ,Change the Isasync to false.

    The data may not be retrieved.

  • Verified answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on 01 Feb 2018 at 07:49:27
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    When using async request you can't return your data directly, you should use "callback" function. Please look at this code example with Sync and Async methods (and be aware for red code lines)

    If your Dynamics CRM version is 365 (v9) you can also use Xrm.WebApi functions to use D365 webapi (https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-webapi), however this methods use Async request, so you need callback or directly code inside this methods.

    You can use CRM REST Builder solution (https://github.com/jlattimer/CRMRESTBuilder) to create your request.

    1. var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(A076D3A1-12F9-E711-A94F-000D3AB50338)?$select=accountid,accountnumber";
    2.  
    3. function mainMethod() {
    4. alternate1_sync(); //do your business inside "req.onreadystatechange"
    5. alternate2_async_with_callback(); //do your business inside callback function "myAsyncCallbackMethod"
    6.  
    7. /*
    8. If "isAsync" parameter is false, XMLHttpRequest running Synchronous and you can get your data out of your function (with return),
    9. otherwise (when Asynchronous process) you should do your business inside "req.onreadystatechange" or use "callback" function inside "req.onreadystatechange" to get data out.
    10. */
    11. }
    12.  
    13. function alternate1_sync() {
    14. var isAsync = false;
    15. var data = null;
    16.  
    17. var req = new XMLHttpRequest();
    18. req.open("GET", apiUrl, isAsync);
    19. req.setRequestHeader("OData-MaxVersion", "4.0");
    20. req.setRequestHeader("OData-Version", "4.0");
    21. req.setRequestHeader("Accept", "application/json");
    22. req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    23. req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    24.  
    25. req.onreadystatechange = function () {
    26. if (this.readyState === 4) {
    27. req.onreadystatechange = null;
    28. if (this.status === 200) {
    29. var result = JSON.parse(this.response);
    30. data = result;
    31. } else {
    32. Xrm.Utility.alertDialog(this.statusText);
    33. }
    34. }
    35. };
    36. req.send();
    37.  
    38. return data;
    39. }
    40.  
    41. function alternate2_async_with_callback() {
    42. var isAsync = true;
    43.  
    44. var req = new XMLHttpRequest();
    45. req.open("GET", apiUrl, isAsync);
    46. req.setRequestHeader("OData-MaxVersion", "4.0");
    47. req.setRequestHeader("OData-Version", "4.0");
    48. req.setRequestHeader("Accept", "application/json");
    49. req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    50. req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    51.  
    52. req.onreadystatechange = function () {
    53. if (this.readyState === 4) {
    54. req.onreadystatechange = null;
    55. if (this.status === 200) {
    56. var result = JSON.parse(this.response);
    57. myAsyncCallbackMethod(result);
    58. } else {
    59. Xrm.Utility.alertDialog(this.statusText);
    60. }
    61. }
    62. };
    63. req.send();
    64. }
    65.  
    66. function myAsyncCallbackMethod(data) {
    67. //you should do your business inside this method
    68. //for example
    69.  
    70. var accountid = data["accountid"];
    71. var accountnumber = data["accountnumber"];
    72.  
    73. if (accountnumber == "123") {
    74. alert("Hello world");
    75. }
    76. }


  • shaikh sharef Profile Picture
    shaikh sharef 80 on 01 Feb 2018 at 05:09:51
    RE: Accessing data retrieved via XMLHttpRequest

    change the method from Async to Sync.

    var req = new XMLHttpRequest();

       req.open("GET", requestPath, false);

       req.setRequestHeader("OData-MaxVersion", "4.0");

  • Suggested answer
    Preeti Sharma Profile Picture
    Preeti Sharma 2,678 on 01 Feb 2018 at 04:40:46
    RE: Accessing data retrieved via XMLHttpRequest

    Hi,

    Please try declaring spirit name as below:

    var spirit_name=null;

    Hope it helps:)

  • DianeF1 Profile Picture
    DianeF1 210 on 31 Jan 2018 at 20:01:50
    RE: Accessing data retrieved via XMLHttpRequest

    Here's the issue.  As long as I'm in the "req.onreadystatechange = function" I can access those items from result.  But once I am past the req.send any of those fields an error is thrown. The "alert("name is" + spirit_name);" states that spirit_name is undefined. I did the var spirit_name at the top of the original code and outside of readystatechange.  How do I get the data outside of readystate function?

  • Suggested answer
    Rawish Kumar Profile Picture
    Rawish Kumar 13,756 on 31 Jan 2018 at 19:53:49
    RE: Accessing data retrieved via XMLHttpRequest

    Hi Diane,

    you will get everything that you have retrieved in "result".

    i see that you have retrieved couple field from spirit_changecontracts entity

    so it would be like :

    var new = result["spirit_changecontractnumber"];

    var new 1 = result["spirit_contractchangenumber"];

    etc

    so whatever fields that you have "select" in the query - you can retrieve them and use anywhere.

    I hope i have answered your question - if not , please correct me :)

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,608 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,558 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans