I have a jQuery function with several nested ajax calls:
function ulozitKlienta () {
//some code
if (!confirm("Není vyplněno datum vstupu klienta!\n\nPřesto uložit?")) return false;
$.ajax({
type : "POST",
cache : false,
url : "ajax/ulozit_klienta.php",
data : JSON.stringify(out),
dataType: "json",
success : function (data) {
if (data.vysledek == "chyba") {
//some code
return false; // TODO ajax return
} else {
if (out["akce"] == "pridat") {
if (data.vysledek == "duplikat") {
$("#js-d-duplikat").dialog({
modal : true,
buttons : {
"Přesto vytvořit nového" : function () {
out["opravdu"] = true;
$.ajax({
type : "POST",
cache : false,
url : "ajax/ulozit_klienta.php",
data : JSON.stringify(out),
dataType: "json",
success : function (data) {
if (data.vysledek == "chyba") {
//some code
return false; // TODO ajax return
} else //some code
},
error : function (data, status, e) {
//some code
return false; // TODO ajax return
}
});
}
}
});
} else //some code
} else //some code
}
},
error : function (data, status, e) {
//some code
return false; // TODO ajax return
}
});
}
I have it in function because I call it from two different points elsewhere:
$("#add_tab").on("click", function() { // založí nový protokol a vytvoří mu tab
if (!ulozitKlienta()) return false;
//some code
});
$("#menu_local").on("click", "[name='ulozit_klienta']", function() {
ulozitKlienta();
});
My problem is, that function ulozitKlienta is not waiting for ajax calls to end and is returning undefined. I thought I use Promise interface as showed here https://stackoverflow.com/a/11283748/836697 but I really don't know how.