There is an Ajax request in the function

function Check_production(order_number){ var result = false; $.ajax({ url: "load/check_production.php", cache: false, async: false, data: {zakaz_number:zakaz_number}, type: 'POST', success: function(data){ if (data == "true"){ result = true; }else { result = false; } } }); return result; 

}

Is it possible to make it more beautiful without turning off an asynchronous request / local variable / in some other way so that Check_production returns the result?

  • one
    no, it is not possible, because it is an asynchronous request. It is necessary to describe through callback, of type function Check_production (order_number, callback) {// ... callback (result); // instead of retouring // or // callback (order_number, result); } - zb '

1 answer 1

Look towards the Deferred object, an example with ajax:

 function SomethingInit(id){ this.init = function(id) { // Загрузка с сервера информации this.load(id).done(function() { // ... здесь продолжается инициализация ... alert("продолжаем после успешного запроса"); }).fail(function(message) { alert('ошибка..') }); }; this.load=function(teamId){ var dfr = $.Deferred(); alert('посылаем запрос'); $.ajax({ url: 'load/check_production.php', success: function(response, status, jqXHR){ dfr.resolve();}, error: function(jqXHR, status, error) { dfr.reject() ; } }); return dfr; //dfr.promise(); }; this.init(); }; 

There are also a number of wrapper libraries for this object, I once liked JSDeferred: http://habrahabr.ru/post/108575/