John
John

Reputation: 1360

jquery ajax call in function returned value

I have for eg code like this

function check(parameters){
some code;
$.post('/url', function(data) {
  //and here I want if data==0 return false from function check
  //if no go and skip to instruction 1
});


   instruction 1;
}

I want in my program later to use if(check(params)==0) but it doesn't seems to working. How i can do this in java script? I need to do if($.post...==0)? Best regards

Upvotes: 0

Views: 339

Answers (2)

Mads Mogenshøj
Mads Mogenshøj

Reputation: 2068

Ajax is asynchronous, if you want to be synchronous you can use the setting in the ajax method. With an asynchronous request, you can provide a callback function. The callback function will then be run when the ajax message returns.

You could call your check function like this, with a callback function after params.

check(params, function(data) {
  if (data == 0) {
    // do something
  } else {
    // do something else
  }
});

And the run the callback in check when the ajax message returns.

function check(parameters, callback){
  some code;
  $.post('/url', function(data) {
    if (typeof callback === 'function') {
      callback(data);
    }
  }  
}

Upvotes: 1

Murali VP
Murali VP

Reputation: 6417

The callback function is not synchronous, meaning it is going to get called at a later time. So you cannot just go to "instruction 1", what you need is in your callback check for data being empty (or whatever your application logic calls for) then call another function that contains "instruction 1". In other words, the caller of check() cannot wait for a response from ajax call.

Upvotes: 0

Related Questions