Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Assigning a variable from ajax response
myObj = {
myAttr: function(){
$.ajax({
type: "GET",
url: myApi,
dataType: "jsonp",
success: function (data) {
return data
}
})
}
}
// in another file footer
var data = myObj.myAttr();
@SamSamskies

This comment has been minimized.

Copy link

commented Dec 27, 2014

You could return the promise returned by the ajax call.

var myObj = {
  myAttr: function(){
    return $.ajax({
        type: "GET",
        url: myApi,
        dataType: "jsonp"
    });
  }
}

// in another file footer
var data;

myObj.myAttr().done(function(response) {
  data = response;
});
@raorao

This comment has been minimized.

Copy link

commented Jan 3, 2015

you can also do some trickery with objects (or variables defined at a higher scope, if you'd like.):

myObj = {
  myAttr: function(){
    $.ajax({
            type: "GET",
            url: myApi,
            dataType: "jsonp",
            success: function (data) {
                myController.data = data;
            }
        })
  }
}

myController = { 
  data: null,
  setData: function() { myObj.myAttr() }
};

myController.setData();
// later on in the code, after another event fires...
$('.el').on('click', function() { console.log(myController.data) })

truthfully, though, you are just hacking around the core of the problem -- JavaScript is asynchronous, and you are trying to make it synchronous. This is always hard in JS, and often results in callback hell. Promises can help, but it may be worth taking a step back and figuring out exactly what you are trying to accomplish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.