To use this tutorial, you need to know the following:
- Know what an HTTP Request is.
- Know what HTTP Request Methods are.
- Know how to use the
Off with the stupidness, lets get programming!
What is an
XMLHttpRequest is just a fancy way in saying:
.json, etc. The name is kind of deceiving as you can actually send requests to other files. Not only
.xml files. The
XMLHttpRequest is part of something called
AJAX. AJAX stands for
asynchronously, or meaning the user doesn't have to reload for the content to update.
Pros and Cons
- Very fast and efficient way of reading files without libraries
- Wide browser support & easy fallback code
- Can read all sorts of files, not only
- Can be easily used to validate forms
- Reduces bandwidth
XMLHttpRequestscan only send requests to local files/pages. So if you sent an
https://exampleSite.com, you wont be able to get data from
https://exampleSite2.com. There is one exception however, you can read
.jsonfiles across the internet.
XMLHttpRequestsare open source, people can easily view the source and change it making your site a bit less secure. Though precautions can be taken.
Step 1: Create the
Step 2: Open gateway.
Step 3: Send Request.
Step 4: Get the response.
Step 5 [OPTIONAL]: Parse the file.
Thank you for reaching the end of the tutorial! If you like it, please UPVOTE!!!
If you have any questions about this topic, you can just comment below. I will try my best to reply with the my best answer!
I'm suprised that no one said
fetch is the modern equivalent of the ancient
XMLHTTPRequest, you might want to look into it too. I prefer
fetch as it feels easier to use. And
fetch avoids callbacks, thus making it much faster and preferred.
Nice! However, please use
let instead of
var is fine, but it causes variable hoisting which can be an issue in larger programs. Also, I would recommend putting in the
xhr.responseText attribute so that beginners who want to use text or JSON can parse the responses. Also, maybe you can do a part 2 with payloads for POST requests?