Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

javascript async woes

This is a newbie JavaScript question, but something I'm not quite sure how to google for help because I'm not sure how to describe the problem in an easy way.

I have a large, somewhat complex JSON that I need to manipulate so that I could reshape the JSON in a way that I get a list of only countries, cities, and sales.

The JSON itself isn't the issue for me, it's what I would like to do with it once I've received it. Basically, I'd like to create 3 separate objects/arrays from a large received JSON and have those 3 separate objects/arrays accessible for usage OUTSIDE of the $.ajax call. Yes, I think I could do all of this inside of the $.ajax success callback, but I'd rather have all the JSON processing done elsewhere. My pseudo JavaScript looks something like this:

var model = {
 countries: [],
 cities: [],
 sales: [],
 set: function(data) {
 //manipulate data here so that model.countries, model.cities, model.sales are populated
 } 
};
$.ajax({
 url: 'example.com/sample.json',
 success: function(data) {
 model.set(data); //is this the right way to do this?
 }
});
$('#countries').html(model.countries);
$('#cities').html(model.cities);
$('#sales').html(model.sales);​

But because JavaScript executes asynchronously, the last 3 lines are always blank because the JSON hasn't been received yet.

So I guess my question is, how do I bind the results of my received JSON to a variable outside of the $.ajax scope so that I could use it wherever on the page?

Answer*

Draft saved
Draft discarded
Cancel

lang-js

AltStyle によって変換されたページ (->オリジナル) /