I have two functions, I need to execute an Ajax function (function 1) before function 2 runs. I am a little confused on how to do this, I think it needs to be done is via a promise but I am a little unclear on how to do that, can an example be given?
function 1:
function showDetails(str) {
return new Promise(function (resolve, reject) {
if (str == "") {
document.getElementById("txtdetails").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtdetails").innerHTML = this.responseText;
}
};
$("#clientrowtestid").val(str);
xmlhttp.open("GET", "getdetails.php?q=" + str, true);
xmlhttp.send();
}
resolve("done");
});
}
function 2:
function sendLate(str) {
showDetails(str).then(function (response) {
var clientn = $("#txtdetails").find("h2").html();
var result;
var r = confirm("Send client (" + str + ") " + clientn + " a late notice?");
if (r == true) {
var taxcb = $("#taxcb").is(":checked") ? 'y' : 'n';
var taxrate = $('#taxrate').val();
var bcctocb = $("#bcctocb").is(":checked") ? 'y' : 'n';
var bcctotxt = $('#bcctotxt').val();
var duedate = $('#duedate').val();
var issuedate = $('#issuedate').val();
var additemscb = $("#additemscb").is(":checked") ? 'y' : 'n';
var additemname = $('#additemname').val();
var additemprice = $('#additemprice').val();
var dayslate = $('#dayslate').val();
var rowid = str;
$.ajax({
type: 'POST',
url: 'sendlate.php',
data: { taxcb: taxcb, taxrate: taxrate, bcctocb: bcctocb, bcctotxt: bcctotxt, duedate: duedate, issuedate: issuedate, additemscb: additemscb, additemname: additemname, additemprice: additemprice, rowid: rowid, dayslate: dayslate },
success: function (response) {
$('#result').html(response);
}
});
} else {
result = "Late notice aborted";
}
document.getElementById("result").innerHTML = result;
});
}
As you can see I need to execute function 1 to propagate the field in which function 2 is gathering data from. Are promises the best way of doing this? Can someone give me an example?