[Solved] Github Commits (Async Programming Task)

  

3
Topic starter

Write a JS program that loads all commit messages and their authors from a github repository using a given HTML.

HTML Template

You are given the following HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Github Commits</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
GitHub username:
<input type="text" id="username" value="nakov" /> <br>
Repo: <input type="text" id="repo" value="nakov.io.cin" />
<button onclick="loadCommits()">Load Commits</button>
<ul id="commits"></ul>
<script>
    function loadCommits() {
        // AJAX call … 
    }
</script>
</body>
</html>

The loadCommits function should get the username and repository from the HTML textboxes with ids "username" and "repo" and make a GET request to the Github API:

"https://api.github.com/repos/<username>/<repository>/commits"

Swap <username> and <repository> with the ones from the HTML:

  • In case of success, for each entry, add a list item (li) in the unordered list (ul) with id= "commits" with text in the format: "<commit.author.name>: <commit.message>"
  • In case of error and a single list item (li) with text in the format: "Error: <error.status> (<error.statusText>)"

Screenshots:

github commits task with javascript

1 Answer
2

>> HERE YOU CAN VIEW AND TEST THE PROJECT ONLINE << (on GitHub io)


My solution is (HTML file first):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Github Commits</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <script src="github-commits.js"></script>
</head>
<body>
GitHub username:
<input type="text" id="username" value="nakov"/> <br>
Repo: <input type="text" id="repo" value="nakov.io.cin"/>
<button onclick="loadCommits()">Load Commits</button>
<ul id="commits"></ul>
</body>
</html>

github-commits.js JavaScript file (the solution):

function loadCommits() {
    $("#commits").empty();
    let url = "https://api.github.com/repos/" +
        $("#username").val() + "/" +
        $("#repo").val() + "/commits";
 
    $.get(url)
        .then(displayCommits)
        .catch(displayError);
 
    function displayCommits(commits) {
        for (let commit of commits) {
            $("#commits").append($("<li>").text(
                commit.commit.author.name + ": " +
                commit.commit.message
            ));
        }
    }
 
    function displayError(err) {
        $("#commits").append($("<li>").text(
            "Error: " +
            err.status + " (" + err.statusText + ")"));
    }
}
Share: