0

I have this piece of code:

$(function(){
    var data = prepData([]);
    alert(data);
    //$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
});

function prepData(query){
    /* TODO: Later afmaken, van het ophalen van gegevens, data en omzetten json doet raar -_- */
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
             var response = xhttp.responseText;
             response = JSON.parse(response);
             //Here i know it works
             return response;
        }
    };
    xhttp.open("POST", "/getData", true);
    xhttp.send();
}

The problem is that when I try to print the data after I call the function var data = prepData([]) it returns undefined, but when I print it inside the onreadystatechange function, that I've marked wit Here i know it works, I get the proper data displayed.

I think the problem is because the function is asynchronous that it finishes before the onreadystatechange gets the chance to return anything, but I don't know how to prevent that.

currarpickt
  • 2,290
  • 4
  • 24
  • 39
Kevin Jansen
  • 59
  • 1
  • 8

0 Answers0