RandomAjax

A JS program that asynchronously get (by using XMLHttpRequest) a sequence of numbers generated by random.org.

by Sabin Buraga

HTML

<div id="numbers">[Wait, please...]</div>

CSS

#numbers {
    font-family: monospace;
    font-size: 1em;
    width: 12em;
}

JavaScript

// a JS program that asynchronously get (by using XMLHttpRequest) a sequence of numbers generated by random.org
const URL = 'https://www.random.org/sequences/?min=1&max=33&col=1&format=plain&rnd=new';
const TIME = 2000;

let numbers = document.getElementById('numbers');

try { // trying to instantiate a XMLHttpRequest object
    var xhr = new XMLHttpRequest();
} catch (e) {
    numbers.textContent = 'XMLHttpRequest cannot be instantiated: ' + e.message;
} finally {  
    xhr.ontimeout = function () { numbers.textContent = 'Time-out... :('; };
    xhr.onload = function () {
        if (xhr.readyState === 4) {   // data arrived
            if (xhr.status === 200) { // response Ok from Web service
                // substituting white spaces with comma and 
                // putting the content into the HTML element identified by 'numbers'
                numbers.textContent = xhr.responseText.trim().replace(/\W+/g, ', ');
            } else {
                numbers.textContent = 'An error occurred: ' + xhr.statusText;
            }
        }
    };
    xhr.open("GET", URL, true); // opening connection
    xhr.timeout = TIME;         // setting the response time
    xhr.send(null);             // sending the HTTP request (no data is provided)
}