There is an ajax query, how to get the result from it and assign it to the variable queryResult, then the queryResult variable should be checked and if something is wrong with its value, you need to exit addPartition ():

function addPartition(){ var queryResult; $.post('controllers/handlerPartition.php', {'isExistPartition': true, 'partitionName': $('#modal_win1_partition_name').val()}, function (result) { return result; //Как получить это значение из вне? } ); if (queryResult === 'false') return; } 

I tried this:

 function addPartition(){ var queryResult; $.post('controllers/handlerPartition.php', {'isExistPartition': true, 'partitionName': $('#modal_win1_partition_name').val()}, function (result) { queryResult = result; //Присвоение внешней переменой } ); alert(typeof queryResult); //undefined if (queryResult === 'false') return; } 

But the value of queryResult is not certain. I understand this because of the asynchrony?

Reported as a duplicate by members of Pavel Mayorov , lexxl , pavel , user207618, aleksandr barakin 12 Aug '16 at 5:33 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Yes, this is due to asynchrony. - Igor
  • And then how to get the value? - VCM
  • The sequence of events is such that result will not be assigned to a queryResult before the function (result) { ... } called. Use queryResult inside callback'a. - Igor
  • I need at a certain result value in the ajax request to exit the external function addPartition () - VCM
  • Hmm, let's do it again. By the time the function (result) { ... } function is addPartition(){ ... } , the addPartition(){ ... } function addPartition(){ ... } work long ago. - Igor

1 answer 1

Use the Promise - it should be returned from your function.

In your case, jQuery provides its version:

 var jqxhr = $.post( "example.php", function() { alert( "success" ); }) .done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); 

You can subscribe to one promise several times:

 jqxhr.always(function() { alert( "second finished" ); }); 

Also notice one of the thread implementations .

An article about functional programming in interface design .