0

I am doing a REST request for an array of objects using JQuery.

In the "success" part of the code everything is fine - the objects in the array are converted to the right type. However, when I try to assign them to a variable (docStructures) and move the variable out of the JQuery method, the objects become "undefined".

How can I avoid this and pass the variable outside of the method's scope persisting the right type of the objects?

jQuery.ajax({
  type: 'GET',
  url: contextPath + "/rest/dcm-jira/1.0/document/structure",
  data: {
    "issueId": selectedRevision.issueId
  },
  success: function(structures) {
    docStructures = structures;
    console.log(docStructures)
  },

});
console.log(docStructures)
Ted
  • 3,985
  • 1
  • 20
  • 33
  • 1
    A for async. $.ajax is async function. I believe async functions handling is the most common js question – Daydreaming Duck Oct 14 '16 at 09:31
  • Um - the way AJAX works is that you're passing a function to be called when you receive a response from the server. What your code is doing currently is - log `docStructures` (last line of code) that hasn't been assigned, do a ajax, when it gets response log `docStructures` again (within success) – eithed Oct 14 '16 at 09:33
  • I cant vote for duplicates yet, this is obvious duplicate: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Daydreaming Duck Oct 14 '16 at 09:34

3 Answers3

1

AJAX is asynchronous, you cannot return anything from it. You should consume the results of an AJAX request only inside the success callback

santosh singh
  • 27,666
  • 26
  • 83
  • 129
1

the problematic line in your code is this:

jQuery.ajax({
  type: 'GET',
  url: contextPath + "/rest/dcm-jira/1.0/document/structure",
  data: {
    "issueId": selectedRevision.issueId
  },
  success: function(structures) {
    docStructures = structures;
    console.log(docStructures)
  },

});
// problematic
console.log(docStructures)

the problem is that it executes before the ajax request has completed. otherwise everything should be working fine

also, you have an extra comma after success:{}, <-- you should delete it

Ted
  • 3,985
  • 1
  • 20
  • 33
0

The success function is executed asynchronously, i.e. the browser executes:

  1. your jQuery.ajax statement
  2. then your console.log statement after the jQuery.ajax statement
  3. then, after the Ajax request has been successful, executes the console.log within the success function

There is no way to have the data outside the scope of the success function.

To make your code look tidier, you can use jQuery's deferred mechanism:

var myAjaxRequest = jQuery.ajax({ 
    type: 'GET',
    url: contextPath + "/rest/dcm-jira/1.0/document/structure",
    data: {
        "issueId": selectedRevision.issueId
    }
});

myAjaxRequest.done(function (structures) {
    docStructures = structures;
    console.log(docStructures)
});
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95