We’re getting a random fact about a certain number! fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

In this article we’re going to use bootstrap as our css framework, NumbersApi to test fetch function. See github repo..

Html page

(How.To.Meet.Ladies)

<!DOCTYPE html>
<html>
<head>
	<title>Numbers Api</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<style>
	#fact { display: none;}
</style>
<body class="bg-dark">
	<div class="container">
		<div class="row">
			<div class="col-md-6 mx-auto">
				<div class="card bg-success mt-5 p-4 text-white">
					<h3>Number Facts</h3>
					<p>Enter a  number and get a random fact.</p>
					<input type="number" id="inputNum" class="form-control form-control-lg" />
					<div id="fact" class="card-body">
						<h4 class="card-title">Number Fact</h4>
						<p id="factText" class="card-text"></p>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
<script>
    let fact = document.querySelector('#fact');
    let factText = document.querySelector('#factText');
    let inputNum = document.querySelector('#inputNum');
    inputNum.addEventListener('input', getFactFetch); //or getFactAjax
</script>
</html>

Using standard ajax

    function getFactAjax()
    {
        let number = inputNum.value;
        let xhr = new XMLHttpRequest();

        xhr.open('GET', 'http://numbersapi.com/'+number);
        xhr.onload = function(){
            if(this.status == 200 && number != ''){
                fact.style.display = 'block';
                factText.innerText = this.responseText;
            }
        }
        xhr.send();
    }

Using fetch api

    function getFactFetch()
    {
        let number = inputNum.value;
        fetch('http://numbersapi.com/'+number)
            .then(response => response.text())
            .then(data => {
                if(number != ''){
                    fact.style.display = 'block';
                    factText.innerText = data;
                }else{
                    fact.style.display = 'none';
                }
            })
            .catch(err => console.log(err))

See full documentation here https://developer.mozilla.org/../Fetch_API