Skip to content
Sign UpLog In
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
12

JavaScript's XMLHttpRequest

ChezCoder
ChezCoder

Hello! Welcome to a tutorial on JavaScript's XMLHttpRequest. Now to get this straight, THIS TUTORIAL IS NOT FOR PEOPLE STARTING JAVASCRIPT. If you want to learn JavaScript, this is NOT the place.

Requirements

To use this tutorial, you need to know the following:

  • How to code in JavaScript.
  • Know what an HTTP Request is.
  • Know what HTTP Request Methods are.
  • Know how to use the document object.

Off with the stupidness, lets get programming!

What is an XMLHttpRequest?

An XMLHttpRequest is just a fancy way in saying: JavaScript's HTTPRequestSender. All it really does is send requests to read files like .txt, .xml, .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 Asynchronous JavaScript and XML. According to Google, AJAX is "a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and JavaScript." Basically, it is a better and faster way of updating webpages asynchronously, or meaning the user doesn't have to reload for the content to update.

Pros and Cons

Pros

  • Very fast and efficient way of reading files without libraries
  • Wide browser support & easy fallback code
  • Can read all sorts of files, not only .xml files
  • Can be easily used to validate forms
  • Reduces bandwidth

Cons

  • XMLHttpRequests can only send requests to local files/pages. So if you sent an XMLHttpRequest from https://exampleSite.com, you wont be able to get data from https://exampleSite2.com. There is one exception however, you can read .json files across the internet.
  • Since XMLHttpRequests are open source, people can easily view the source and change it making your site a bit less secure. Though precautions can be taken.

Code

Step 1: Create the XMLHttpRequest obj.

// create new XMLHttpRequest var xhr = new XMLHttpRequest();

Step 2: Open gateway.

// create new XMLHttpRequest var xhr = new XMLHttpRequest(); // open gateway xhr.open("GET","ajax.txt");

Step 3: Send Request.

// create new XMLHttpRequest var xhr = new XMLHttpRequest(); // open and send gateway xhr.open("GET","ajax.txt"); xhr.send(); // the parameters would be the params for sending requests to servers, like q=search&user=example

Step 4: Get the response.

// create new XMLHttpRequest var xhr = new XMLHttpRequest(); // open and send gateway xhr.open("GET","ajax.txt"); xhr.send(); // the parameters would be the params for sending requests to servers, like q=search&user=example xhr.onreadystatechange = function() { // if state of response = 4, or DONE, and HTTP status = 200, write response is ready! if (xhr.readyState == 4 && xhr.status == 200) { window.alert(xhr.responseText) //alert response! } }

Step 5 [OPTIONAL]: Parse the file.

// create new XMLHttpRequest var xhr = new XMLHttpRequest(); // open and send gateway xhr.open("GET","ajax.txt"); xhr.send(); // the parameters would be the params for sending requests to servers, like q=search&user=example xhr.onreadystatechange = function() { // if state of response = 4, or DONE, and HTTP status = 200, write response is ready! if (xhr.readyState == 4 && xhr.status == 200) { parseXML(xhr); } } function parseXML(xml) { // convert XML to an HTML Document var xmlDoc = xhr.responseXML; // treat the new parsed XML like a regular DOM Object! var i = 0; for(var i = 0;i < xmlDoc.getElementsByTagName("name").length;i++) { document.write(xmlDoc.getElementsByTagName("name")[i].textContent) } }

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!

:P

References

3 years ago

Voters

Comments

TopNew
3
Muffinlavania
Muffinlavania

Heres some attention, and also the equation to life

Pizza+Nodejs=ChezCoder

But one small tweak...

(Pizza+Nodejs=ChezCoder)<Muffinboi

2 years ago
1
ChezCoder
ChezCoder

@Muffinlavania
lol

2 years ago
1
Bookie0
Bookie0

Pretty neat!

2 years ago
1
AmazingMech2418
AmazingMech2418

Nice! However, please use let instead of var. 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?

3 years ago
1
ChezCoder
ChezCoder

@AmazingMech2418
yes but we dont want to get confused with those yet

3 years ago
1
AmazingMech2418
AmazingMech2418

@ChezCoder
After learning about variable hoisting, I just started always using let... I know some people prefer const because of its relative immutability, but I always just use let.

3 years ago
1
ChezCoder
ChezCoder

@AmazingMech2418
lol, also step 5 is optional, the actual finished product is step 4

3 years ago
1
AmazingMech2418
AmazingMech2418

@ChezCoder
Oops. Accidentally skipped over that...

3 years ago
1
ChezCoder
ChezCoder

@AmazingMech2418
i use let when a variable is going to be local (in functions, etc) and var is global. Const is for things I wont be changing but of course, i didn't learn about it at the time I made this (this was a repost because it got like 0 upvotes and comments before)

3 years ago
1
ChezCoder
ChezCoder

@AmazingMech2418
lol, its ok, i shoulld probably note that, my fault

3 years ago
1
AmazingMech2418
AmazingMech2418

@ChezCoder
I guess var would be useful for global variables... I just find it easier to just use let so that, let's say if I were to move a basic script to a function or a class, I wouldn't have to change anything to change the scope of the variables.

3 years ago
1
ChezCoder
ChezCoder

@AmazingMech2418
lol, i think you misunderstood me, I just use var and let so when I look back in the code, I can see if the variable was global or local during debugging

3 years ago
1
AmazingMech2418
AmazingMech2418

@ChezCoder
Oh... I thought you meant that you used the variable hoisting to your advantage to make global variables remain global.

3 years ago
0
xxpertHacker
xxpertHacker

I'm suprised that no one said fetch yet. 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.

3 years ago
Load more