4 Min

CRUD (Create, Read, Update, Delete) applications are one of the most fundamental tasks in web development. Understanding CRUD operations is key to building dynamic, data-driven websites or apps. This cheat sheet will guide you through the basic CRUD concepts, providing simple explanations, examples, and tips on how to implement these operations. Whether you’re a beginner in JavaScript, HTML, or web development in general, this post will help you to clarify things


What is CRUD?

CRUD stands for Create, Read, Update, and Delete — the four basic operations you can perform on data in an application.

  • Create: Add new data (e.g., adding a new user, creating a new blog post)
  • Read: Retrieve or display existing data (e.g., displaying a list of users or blog posts)
  • Update: Modify existing data (e.g., editing a user’s profile)
  • Delete: Remove data (e.g., deleting a blog post)

CRUD Operations Overview

CRUD operations are usually performed on data stored in databases, and they are typically handled using a combination of HTML, JavaScript, and a backend server. Here’s how each CRUD operation works conceptually and how it can be implemented in your web app.


1. Create (C)

Create allows users to add new data to the application.

How it works:

  • The user fills out a form (e.g., a sign-up form or a “New Post” form).
  • The form data is sent to the backend (server) using a method like POST.
  • The backend stores the data in a database.

Example:

HTML form for creating a new user:

<form id="userForm">
  <input type="text" name="username" placeholder="Username" required />
  <input type="email" name="email" placeholder="Email" required />
  <button type="submit">Create User</button>
</form>

JavaScript code to handle the form submission:

document.getElementById('userForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const formData = {
    username: e.target.username.value,
    email: e.target.email.value,
  };

  fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(formData)
  })
  .then(response => response.json())
  .then(data => console.log('User created:', data))
  .catch(error => console.error('Error:', error));
});

2. Read (R)

Read lets you fetch and display data from the database.

How it works:

  • The frontend makes a request to the backend (usually using the GET method) to fetch data.
  • The backend retrieves the data from the database and sends it back to the frontend.
  • The frontend displays the data (e.g., a list of users, blog posts, or products).

Example:

JavaScript code to fetch and display a list of users:

fetch('/api/users')
  .then(response => response.json())
  .then(users => {
    const userList = document.getElementById('userList');
    users.forEach(user => {
      const listItem = document.createElement('li');
      listItem.textContent = `${user.username} (${user.email})`;
      userList.appendChild(listItem);
    });
  })
  .catch(error => console.error('Error:', error));

HTML structure for displaying users:

<ul id="userList"></ul>

3. Update (U)

Update modifies existing data, such as editing a profile or changing a post’s content.

How it works:

  • The user edits existing data using a form or an interface.
  • The updated data is sent to the backend (typically using the PUT or PATCH method).
  • The backend updates the record in the database.

Example:

HTML form for updating user data:

<form id="updateForm">
  <input type="text" name="username" placeholder="New Username" required />
  <input type="email" name="email" placeholder="New Email" required />
  <button type="submit">Update User</button>
</form>

JavaScript code to handle updating the user:

document.getElementById('updateForm').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const updatedData = {
    username: e.target.username.value,
    email: e.target.email.value,
  };

  fetch('/api/users/1', { // Assuming the user ID is 1
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updatedData)
  })
  .then(response => response.json())
  .then(data => console.log('User updated:', data))
  .catch(error => console.error('Error:', error));
});

4. Delete (D)

Delete removes data from the database, such as deleting a user or removing a blog post.

How it works:

  • The user clicks a button to delete data.
  • The frontend sends a request to the backend using the DELETE method.
  • The backend removes the data from the database.

Example:

JavaScript code to delete a user:

function deleteUser(userId) {
  fetch(`/api/users/${userId}`, { method: 'DELETE' })
    .then(response => response.json())
    .then(data => console.log('User deleted:', data))
    .catch(error => console.error('Error:', error));
}

// Assuming a delete button for user with ID 1
document.getElementById('deleteBtn').addEventListener('click', () => deleteUser(1));

HTML for a delete button:

<button id="deleteBtn">Delete User</button>

CRUD in the Real World: Tips for Beginners

  1. Start Small: When learning CRUD operations, start by building small applications, such as a simple to-do list or a basic user management system.

  2. Use RESTful APIs: CRUD operations are often built around RESTful APIs. Learn how HTTP methods (GET, POST, PUT, DELETE) map to CRUD actions.

  3. Focus on Security: When performing CRUD operations, ensure that your app has basic security measures in place, like validating user input and authenticating requests.

  4. Practice with JSON Data: Since most CRUD applications deal with data, you’ll often work with JSON when sending data between the frontend and backend.

  5. Test Your API Calls: Use tools like Postman or cURL to test your CRUD operations before connecting them to your frontend.


Conclusion

CRUD applications are the foundation of many modern web apps. By mastering these operations, you’ll gain a better understanding of how to work with data in web development. Whether you’re building a small project or contributing to a larger app, these skills will serve as your core toolkit. As you practice creating, reading, updating, and deleting data, you’ll see how easy and powerful web development can become!

Happy coding!

Updated: