JavaScript Event Listener and AJAX Hello World!

Week 4 of HTML, CSS, and Javascript for Web Developers!

Event Handler Hello World

index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <script src="js/script.js"></script>
</head>
<body>
    <h1 id="title">Hello World</h1>
    <p>
        Say hello to <input id="name" type="text"/>
        <button>Say it!</button>
    </p>
    <div id="content"></div>
</body>
</html>

script.js
document.addEventListener("DOMContentLoaded", function() {
    document.querySelector("button").onclick = function () {
        var name = document.getElementById("name").value;
        var message = "<h2>Hello " + name + "!</h2>";
        document.getElementById("content").innerHTML = message;
    }
});

AJAX Hello World

Directory Layout
index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ajax Example!</title>
    <script src="js/ajax-utils.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
    <h1 id="title">Ajax Example!</h1>
    <div>
        <button>Say Hello using AJAX!</button>
    </div>
    <div id="content"></div>
</body>
</html>

ajax-utils.js
(function () {
    var ajaxUtils = {};
 
    // Makes an Ajax GET request to 'requestUrl'
    ajaxUtils.sendGetRequest = function (requestUrl, responseHandler) {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                responseHandler(request);
            }
        };
        request.open("GET", requestUrl, true);
        request.send(null); // for POST only
    };
 
    // Expose utility to the global object
    window.$ajaxUtils = ajaxUtils;
})();

script.js
document.addEventListener("DOMContentLoaded", function () {
    var responseHandler = function (request) {
        var name = request.responseText;
        console.log("Name is: " + name);
        var koraytugay = JSON.parse(name);
        console.log(koraytugay);
        document.querySelector("#content").innerHTML
            = "<h2>Hello " + koraytugay + "!</h2>";
    };
    document.querySelector("button").addEventListener("click", function () {
        $ajaxUtils.sendGetRequest("data/name.json", responseHandler);
    });
});