I have some issues with your code and possible alternatives for implementation.
Usage of var
In Javascript using var
instead of let
or const
are somewhat discouraged (in the new era of ES6). There is some value in block scope for loops using var
but you can certainly always use ES6' let
instead. Since you are not reassigning xmlHttp
you might as well const
that (same goes for x
and let
for url
).
Use fetch
instead of XMLHttpRequest
Fetch comes with a promise-ready easier API for handling requests. CanIUse reports that it's almost supported on every new Browser as well. A polyfill should be enough to support the rest of the browsers out there. It also helps in readability and simplicity.
In your case, getting HTML out of a requests is a simple as:
fetch(...) .then(function (response) { // Status 200? Type text/html? Might aswell check that here. return response.text(); }) .then(function (body) { // Insert into dom here... console.debug(body); })
Error handling thanks to fetch
What happens if your URL is faulty, temporarily unavailable and some other error? If you need error handling then just add a catch below then
:
.catch(e){ // Display message, console silenty console.debug(e); }
Using external libraries is usually not necessary as ES6 brings the most bang for the buck anyway.