You request synchronous requests: the function should not be returned until its return value has been calculated, even if it is associated with 100 milliseconds of server request for data.
By setting the third argument xhr.open to true , you use asynchronous requests - telling the browser that you want your function to return before a response is received from the server . Which pretty much means that it cannot return the elements since they have not yet been received.
Of course, using synchronous requests is a pain in the user interface, because your javascript is basically blocked until the response comes back a few hundred milliseconds later (if you're lucky).
It is recommended that you correctly configure JavaScript code to account for asynchronous messages and allow the return of values through a callback instead of return . You do not have to, but in the end it will save you a lot of pain.
source share