0

I'm trying to make a variable depend on the callback from an AJAX get function, however; I can't seem to get it working. I want to make sure that defaults.context always has a value before proceeding any other code.

What am I doing wrong or how can I achieve this in a proper way?

var defaults = {
     currentCase: undefined,
     context: {}
  }

  // Set defaults
  function initDefaults(){
     defaults.currentCase = getCurrentCase();
     defaults.context = getContext(defaults.currentCase, function(object){
        console.log(object); // logs the right data
        return object;
     });
     console.log(defaults.context); // logs undefined
  }

  initDefaults();

  // Get the ID of the current case
  function getCurrentCase(){
     return global_vars.project_ID;
  }

  function getContext(id, callback){
     var obj = {};

     $.get(global_vars.template_url + "/includes/load-project-context.php?id=" + id, function(data) {
        obj = JSON.parse(data);
     }).complete(function() {
        callback(obj);
     });
  }

Thanks in regards,

Enzio

Enzio
  • 377
  • 4
  • 15
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Jan 29 '16 at 11:36
  • 1
    Looks like you're already aware of the concept of callbacks as you're passing one to `getContext`. You just need to carry on using callbacks as necessary. – James Thorpe Jan 29 '16 at 11:36
  • 1
    You are trying to output `defaults.context` before the ajax request finished. So in the moment when you call `console.log` the `defaults.context` is not defined yet. – mickiewicz Jan 29 '16 at 11:44

3 Answers3

0

You can use something like

global_vars.template_url + "/includes/load-project-context.php?id=" + id, function(data) {
    obj = JSON.parse(data);
 }).complete(function() {
    callback(obj);
 }).fail(function() {
    callback(error);
 });

This is callback chaining. You can use other callbacks to handle other use cases.

0

May be you should continue the further code in ajax callback.

// Set defaults
function initDefaults() {
    defaults.currentCase = getCurrentCase();
    getContext(defaults.currentCase, function(object) {
        defaults.context = object;     // Continue your code inside here
        console.log(defaults.context); // Logs the right data
        return object;
    });

    // This will still return `undefined` because this line will be executed
    // before the ajax request finishes. 
    console.log(defaults.context); 
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
NeiL
  • 791
  • 8
  • 35
0

Please check How to know when all ajax calls are complete

You will find there all what you need with quite good explanation

Community
  • 1
  • 1
mickiewicz
  • 279
  • 2
  • 13