Native Ajax Example

JS
S
JavaScript

Demonstrates basic implementation of native JavaScript AJAX requests without using external libraries. Ideal for beginners learning asynchronous web programming fundamentals.

1<h1> Ajax Demo Page </h1>
2<script>
3  // IIFE
4  (function () {
5    const httpRequest = new XMLHttpRequest();
6    if (!httpRequest) {
7      console.log('Giving up :( Cannot create an XMLHTTP instance');
8      return false;
9    }
10    httpRequest.onreadystatechange = printContents;
11    httpRequest.open('GET', 'http://localhost:3600/');
12    httpRequest.send();
13
14    function printContents() {
15      if (httpRequest.readyState === XMLHttpRequest.DONE) {
16        if (httpRequest.status === 200) {
17          console.log(httpRequest.responseText);
18        } else {
19          console.log('There was a problem with the request.');
20        }
21      }
22    }
23  })();
24</script>

Created on 9/25/2018