0

I have the following function in javascript:

function checkFunc(msg) {
  $.getJSON("myurl.php", {
    dtccode: msg
  }, function(j) {
    return j.boolField;
  }); //JSON call
}

And I call it in another function:

function check(msg) {
  var ret = checkFunc1(); //some other function
  ret = checkFunc2() && ret; //some other function
  ret = checkFunc3() && ret; //some other function
  ret = checkFunc() && ret;
  if (ret) {
    //code
  }
}

My problem is, that I know the checkFunc should return false, but it returns true. I think this may be a synchronization issue, but I don't know what to do.

Can anyone help?

1 Answers1

2

AJAX is asynchronous. Means that you have to use callback function to get the result. Like so:

function checkFunc(msg, callback) {
  $.getJSON("myurl.php", {
    dtccode: msg
  }, function(j) {
    callback(j.boolField);
  }); //JSON call
}

and

function check(msg) {
  checkFunc(msg, function(result){
     alert(result);
  }); 
}

EDIT: Using deferred system:

$.getJSON("myurl.php").done(function(j) {
    callback(j.boolField);
});

You can also add fail() to check for possible error. Check the docs: http://api.jquery.com/jquery.getjson/

Ivan Sivak
  • 7,178
  • 3
  • 36
  • 42