Learn to Code via Tutorials on Repl.it

← Back to all posts
The XMLHttpRequest
ChezCoder (214)

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: Done!. (IF XML FILE: Parse the XML [OPTIONAL])

// 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)
    }
}

EXAMPLE REPL

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