How to return a variable(string) from Ajax using only vanilla Javascript I am trying to use Ajax to return a string. But when I print the string, it returns Undefined.
Ajax code:
function loadDoc() {
var output;
var code;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
output = this.responseText;
var parseOutput = JSON.parse(output); // The output we get is in JSON format
code = '<table style="width:100%">';
for (var i = 0; i < parseOutput.records.length; i++){
code = code +'<tr>'
+'<td style="display:flex; flex-wrap: wrap; border:1px solid grey; border-radius: 25px;">'+'<div style="margin:0.5em;">'
+'ITEM : ' + parseOutput.records[i].skuID
+'</div>'
//+....other fields
+'</td>'
+'</tr>';
}
code = code + '</table>';
//document.getElementById(EIS).innerHTML = code; (If i just print the variable code in here, the result can be shown)
return code;
};
xhttp.open("GET", "http://localhost/eis/api/skus/read.php", true);
xhttp.send();
}
I would like to output the variable code in another function:
function output_result(){
var code = loadDoc();
$wrapper.append('<div class="new_crew_form_wrapper">'
+ '<div class="general_header">Add From XXX System</div>'
+ '<div class="general_status"></div>'
+ '<p id="XXX">Test</p>'
+ code); // I would like the result (variable) of Ajax to be inserted here
}