Let's Build a CRUD Website with HTML, CSS, JavaScript and an External API

By Karn Yongsiriwit

June 12th, 2021

image

In this article, we will give you a tutorial for creating a web application with just only basic HTML, CSS and JavaScript (based on Bootstrap 5) to perform CRUD operations. Well, CRUD operations are the four basic operations of manipulating data including Create/Construct, Read, Update and Delete. Furthermore, our CRUD operations will perform by the use of an external API from MeCallAPI.com. If you want to try a mockup API for CRUD and authentication operations, feel free to check on the website.

https://www.mecallapi.com/crud/

https://www.mecallapi.com/

You can also check an example of what we want to achieve in this article here: https://www.mecallapi.com/crud/

https://www.mecallapi.com/crud/

https://www.mecallapi.com/

Software Installation

You only need a Text Editor/IDE (VS Code, Notepad, etc.) and a web browser (Chrome, Firefox, Edge, etc.) to do this tutorial!

Let's Code! (HTML and CSS)

Staring for the HTML which are documents designed to be displayed in a web browser. There are more than a hundred of HTML elements you can choose to put on your HTML file and make the magic happen.

Create index.html with the following links:

  • Bootstrap 5 framework to make your life easier to create a responsive web (line 9 and 54)

  • Sweetalert for easily creating nice popups using JavaScript (line 53)

  • index.css for defining extra CSS (Cascading Style Sheets) to style your index.html in addition from the Bootstrap (line 13)

  • index.js for JavaScript using in index.html to call API for CRUD operations (line 52)

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <title>CRUD FROM API</title>

    <link href="index.css" rel="stylesheet">
  </head>
  <body>

    <nav class="navbar navbar-dark bg-mynav">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">My App</a>
      </div>
    </nav>

    <div class="container">
      <div class="d-flex bd-highlight mb-3">
        <div class="me-auto p-2 bd-highlight"><h2>Users</div>
        <div class="p-2 bd-highlight">
          <button type="button" class="btn btn-secondary" onclick="showUserCreateBox()">Create</button>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Avatar</th>
              <th scope="col">First</th>
              <th scope="col">Last</th>
              <th scope="col">Username</th>
              <th scope="col">Action</th>
            </tr>
          </thead>
          <tbody id="mytable">
            <tr>
              <th scope="row" colspan="5">Loading...</th>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <script src="index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  </body>
</html>

Create index.css to define extra CSS (Cascading Style Sheets) for your index.html in addition from the CSS provided by Bootstrap.

.bg-mynav {
  background-color: #2c3e50;
}

body {
  font-size: 1.25rem;
  background-color: #f6f8fa;
}

td {
  line-height: 3rem;
}

Read operation (JavaScript)

Create file index.js to call an API for CRUD operations starting from Read.
API URL: https://www.mecallapi.com/api/users
Method: GET

To read data with JavaScript, we will use AJAX (Asynchronous JavaScript And XML) technique to have our web site update asynchronously. Concretely, we will have data exchange using API in the background. Thus, the data is retrieved, we will have our web page updated without doing a refresh.

We will use XMLHttpRequest to call an API for retrieving data in JSON and display/update such data on the web page. To update the data on the web page, we will manipulate HTML DOM (Document Object Model). In our code, we will update the data in table by referring to the id of the HTML data table element, namely (mytable) in line 21.

function loadTable() {
  const xhttp = new XMLHttpRequest();
  xhttp.open("GET", "https://www.mecallapi.com/api/users");
  xhttp.send();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
      var trHTML = "";
      const objects = JSON.parse(this.responseText);
      for (let object of objects) {
        trHTML += "<tr>";
        trHTML += "<td>" + object["id"] + "</td>";
        trHTML +=
          '<td><img width="50px" src="' +
          object["avatar"] +
          '" class="avatar"></td>';
        trHTML += "<td>" + object["fname"] + "</td>";
        trHTML += "<td>" + object["lname"] + "</td>";
        trHTML += "<td>" + object["username"] + "</td>";
        trHTML +=
          '<td><button type="button" class="btn btn-outline-secondary" onclick="showUserEditBox(' +
          object["id"] +
          ')">Edit</button>';
        trHTML +=
          '<button type="button" class="btn btn-outline-danger" onclick="userDelete(' +
          object["id"] +
          ')">Del</button></td>';
        trHTML += "</tr>";
      }
      document.getElementById("mytable").innerHTML = trHTML;
    }
  };
}

loadTable();

Open index.html on a web Browser, you will see the result:

Data from the API showing

Data from the API showing

Create operation (JavaScript)

API URL: https://www.mecallapi.com/api/users/create
Method: POST
Sample body (JSON):

{
    "fname": "Cat",
    "lname": "Chat",
    "username": "cat.chat@mecallapi.com",
    "email": "cat.chat@mecallapi.com",
    "avatar": "https://www.mecallapi.com/users/cat.png"
}

Add the following code in index.js

function showUserCreateBox() {
  Swal.fire({
    title: "Create user",
    html:
      '<input id="id" type="hidden">' +
      '<input id="fname" class="swal2-input" placeholder="First">' +
      '<input id="lname" class="swal2-input" placeholder="Last">' +
      '<input id="username" class="swal2-input" placeholder="Username">' +
      '<input id="email" class="swal2-input" placeholder="Email">',
    focusConfirm: false,
    preConfirm: () => {
      userCreate();
    },
  });
}

function userCreate() {
  const fname = document.getElementById("fname").value;
  const lname = document.getElementById("lname").value;
  const username = document.getElementById("username").value;
  const email = document.getElementById("email").value;

  const xhttp = new XMLHttpRequest();
  xhttp.open("POST", "https://www.mecallapi.com/api/users/create");
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhttp.send(
    JSON.stringify({
      fname: fname,
      lname: lname,
      username: username,
      email: email,
      avatar: "https://www.mecallapi.com/users/cat.png",
    })
  );
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      const objects = JSON.parse(this.responseText);
      Swal.fire(objects["message"]);
      loadTable();
    }
  };
}

Refresh index.html and try to perform the create operation:

Click Create

Click Create

Input data

Input data

New data is added

New data is added

UPDATE operation (JavaScript)

API URL: https://www.mecallapi.com/api/users/update
Method: PUT
Sample body (JSON):

{
    "id": 11,
    "fname": "Cat",
    "lname": "Gato",
    "username": "cat.gato@mecallapi.com",
    "email": "cat.gato@mecallapi.com",
    "avatar": "https://www.mecallapi.com/users/cat.png"
}

Add the following code in index.js

function showUserEditBox(id) {
  console.log(id);
  const xhttp = new XMLHttpRequest();
  xhttp.open("GET", "https://www.mecallapi.com/api/users/" + id);
  xhttp.send();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      const objects = JSON.parse(this.responseText);
      const user = objects["user"];
      console.log(user);
      Swal.fire({
        title: "Edit User",
        html:
          '<input id="id" type="hidden" value=' +
          user["id"] +
          ">" +
          '<input id="fname" class="swal2-input" placeholder="First" value="' +
          user["fname"] +
          '">' +
          '<input id="lname" class="swal2-input" placeholder="Last" value="' +
          user["lname"] +
          '">' +
          '<input id="username" class="swal2-input" placeholder="Username" value="' +
          user["username"] +
          '">' +
          '<input id="email" class="swal2-input" placeholder="Email" value="' +
          user["email"] +
          '">',
        focusConfirm: false,
        preConfirm: () => {
          userEdit();
        },
      });
    }
  };
}

function userEdit() {
  const id = document.getElementById("id").value;
  const fname = document.getElementById("fname").value;
  const lname = document.getElementById("lname").value;
  const username = document.getElementById("username").value;
  const email = document.getElementById("email").value;

  const xhttp = new XMLHttpRequest();
  xhttp.open("PUT", "https://www.mecallapi.com/api/users/update");
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhttp.send(
    JSON.stringify({
      id: id,
      fname: fname,
      lname: lname,
      username: username,
      email: email,
      avatar: "https://www.mecallapi.com/users/cat.png",
    })
  );
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      const objects = JSON.parse(this.responseText);
      Swal.fire(objects["message"]);
      loadTable();
    }
  };
}

Refresh index.html and try to perform the update operation:

Edit the newly added user

Edit the newly added user

Input data

Input data

Data is updated

Data is updated

DELETE operation (JavaScript)

API URL: https://www.mecallapi.com/api/users/delete
Method: DELETE
Sample Body (JSON):

{
    "id": 11
}

Add the following code in index.js

function userDelete(id) {
  const xhttp = new XMLHttpRequest();
  xhttp.open("DELETE", "https://www.mecallapi.com/api/users/delete");
  xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhttp.send(
    JSON.stringify({
      id: id,
    })
  );
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4) {
      const objects = JSON.parse(this.responseText);
      Swal.fire(objects["message"]);
      loadTable();
    }
  };
}

Refresh index.html and try to perform the delete operation:

Delete the newly added user

Delete the newly added user

Popup is showing

Popup is showing

Data is deleted

Data is deleted

Conclusion

That's a wrap! Hopefully, this tutorial will help you understanding the basic of developing web application by using just HTML, CSS, and JavaScript. With the basic that you have, I strongly believe that you will be able to faster adopt popular frameworks in the market, such as, React, Angular, Vue. And in some cases, you might not need to use those frameworks at all.



Continue Learning