2

Suppose I have a JSON as follows

[{"skill":"java"},{"skill","js"},{"skill","jquery"}]

I need to find if the entered skill is available in JSON

function checkSearchQuery(query){
    $.getJSON('assets/static/json/keywords.json',function(data){
        $.each(data, function() {  
            if(query.toLowerCase() == this.skill.toLowerCase()) { 
                return true; 
            } 
         });
     });
}

I am checking like this

if(checkSearchQuery("Java")) {
       // Do the action
}
else {
       // Do else part
}

But this seems to execute the else part always.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
raghav
  • 285
  • 2
  • 12
  • checkSearchQuery is an async call – tymeJV Mar 03 '14 at 20:31
  • It's always evaluating the `else` block because `checkSearchQuery()` isn't actually `return`ing anything. Since `$.getJSON()` is asynchronous, the `return` statement is evaluated after the `if`. The `return` is also within `function(data){...}` and will apply to that function instead. – Jonathan Lonowski Mar 03 '14 at 20:34

2 Answers2

1

Since you are making an asynchronous call within checkSearchQuery(), the if condition will be evaluated before the function ever returns. You need to understand this and either do your work in the success handler, or utilize the deferred object using something like done(). For example:

$.getJSON('assets/static/json/keywords.json',function(data){
    $.each(data, function() {  
        if(query.toLowerCase() == this.skill.toLowerCase()) { 
            return true; 
        } 
     });
 }).done(function(..)) {
     // perform some action
 });
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

$.getJSON works async, you should send a callback function,

function checkSearchQuery(query, callback){
    var result = false;
    $.getJSON('assets/static/json/keywords.json',function(data){
        $.each(data, function() {  
            if(query.toLowerCase() == this.skill.toLowerCase()) { 
              result = true;  
            } 
         });
         callback(result);
     });
}

checkSearchQuery("Java", function(result) {
  if (result == true) {
    //do the action
  } else {
    //do else part.
  }
});
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129