I have a function that I wish to dynamically generate an HTML table using data that it grabs from an SQL call. As you can see the function receives a groupID and passes it to a function populateDB
, which when called will perform an AJAX call to retrieve some data from a DB. I need that data from that AJAX call immediately after the AJAX call before the next lines of code are executed. I know that AJAX is asynchronous and that the rest of the code will execute probably before the data is returned from the AJAX call. I also know that the use of callback functions often help in these situations. I have read this stack post over and over: How do I return the response from an asynchronous call?
However, in this instance, and after hours of problem solving, I cannot see how I can program a callback to work for me here. I am sure I am just not clever enough but I would be so grateful for someone to lend me a hand and show me how I can call the populateDB
function and wait for a response, then get that response back into the makeEditTableHTML
function for further processing.
function makeEditTableHTML(studentArray, groupID) {
populateDB(groupID);
--- I NEED THE DATA/ARRAY FROM THE AJAX CALL HERE ---
var result = "<table id='dataEditTableid' class='stripe' border=1><thead><tr><td><b>ID</b></td><td><b>Student Email</b></td><td><b>Group ID</b></td><td><b>Target</b></td><td><b>SEN</b></td><td><b>Disadvantaged</b></td></tr></thead>";
result += "<tbody>";
for(var i=0; i<studentArray.length; i++) {
result += "<tr>";
result += "<td>"+studentArray[i][1]+"</td>";
result += "<td>"+studentArray[i][0]+"</td>";
result += "<td>"+groupID+"</td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(1, this.id, this.innerHTML, "+groupID+")'></td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(2, this.id, this.innerHTML, "+groupID+")'></td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(3, this.id, this.innerHTML, "+groupID+")'></td>";
result += "</tr>";
}
result += "</tbody></table>";
return result;
}
AJAX call function:
function populateDB(groupID) {
$(document).ready(function(){
$.ajax({
type: "POST",
url: {$js_url} + '/wp-content/plugins/WickCustomLD/sqlPopulateDB.php',
data: {"groupID" : groupID},
success: function(data) {
data = JSON.parse(data);
},
})});
}
Original makeEditTableHTML
function call code:
var result_table = makeEditTableHTML(MultiStudList[groupIndex], groupIDs[groupIndex]);
dataTable.innerHTML = result_table;