baron
baron

Reputation: 11191

jQuery/javascript basic logic question

I am using a jQuery method $.getJSON to update data in some cascading drop down lists, in particular, a default value if there is nothing returned for the drop down, e.g. "NONE".

I just want some clarification to how my logic should go.

var hasItems = false; 
$.getJSON('ajax/test.json', function(data) {
hasItems = true;

    //Remove all items
    //Fill drop down with data from JSON


});

if (!hasItems)
{
    //Remove all items
    //Fill drop down with default value
}

But I don't think this is right. So do I enter into the function whether or not I receive data? I guess I really want to check the data object contains something - to set my boolean hasItems.

Upvotes: 1

Views: 634

Answers (3)

Chris Moschini
Chris Moschini

Reputation: 37997

You're dealing with asynchrony, so you need to think of the code you're writing as a timeline:

+ Some code
+ Fire getJSON call
|
| server working
|
+ getJSON call returns and function runs

The code inside the function happens later than the code outside it.

Generally:

// Setup any data you need before the call

$.getJSON(..., function(r) { //or $.ajax() etc
    // Handle the response from the server
});

// Code here happens before the getJSON call returns - technically you could also
// put your setup code here, although it would be weird, and probably upset other
// coders.

Upvotes: 1

J.W.
J.W.

Reputation: 18181

You should handle the check right inside the callback function, check the example here.

var hasItems = false; 
$.getJSON('ajax/test.json', function(data) {
hasItems = true;

    //Remove all items
    //Fill drop down with data from JSON
if (!hasItems)
{
    //Remove all items
    //Fill drop down with default value
}

});

Upvotes: 6

alex
alex

Reputation: 490647

You want to do all checking of returned data inside the callback, otherwise that condition will be called before the callback has been called, resulting in it always being the initial value assigned.

Upvotes: 6

Related Questions