0

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
 }
If i just print the variable code in here, the result can be shown. However, if I want to return the variable code from Ajax, it becomes undefined. How can I fix this? Thank You. Please do not give answers that use jQuery. Thank You.
Programmer
  • 151
  • 1
  • 12
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Grundy Jun 07 '18 at 03:54

1 Answers1

0

The "return code;" statement is not returning from loadDoc(), it is returning from the onreadystatechange function, which will go nowhere. You might want this:

// change 
function loadDoc() {
// to
function loadDoc(func1) {

// change
return code;
// to
func1(code);

// then
function output_result() {
  loadDoc(function(stuff) { 
    $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>'
    + stuff);
  } )
}

EDIT: Corrected it.

dcromley
  • 1,373
  • 1
  • 8
  • 23