DEV Community

 Precious Kelvin Nwaogu
Precious Kelvin Nwaogu

Posted on

1

Integrating APIs with frontend framework jQuery

Introduction

In modern web development, the ability to seamlessly connect your frontend with backend APIs is vital for creating dynamic and user-friendly applications. This guide focuses on integrating API calls into a frontend framework using jQuery, specifically within the context of a Shopping Cart CRUD Application powered by a Spring Boot REST API. By leveraging jQuery's powerful AJAX capabilities, you can build an interactive shopping list application that performs Create, Read, Update, and Delete (CRUD) operations efficiently.

To follow along, ensure you have a functioning Spring Boot backend configured with a MySQL database and populated product data. The backend API for this example operates at http://localhost:8080/api/v1/products. With this setup, you’ll explore how to use jQuery's $.ajax() method for asynchronous communication between the frontend and backend, enhancing user experience without the need for page reloads.

Learning Outcomes

1. Introduction to AJAX: AJAX allows asynchronous communication between the frontend and backend. With jQuery, $.ajax() makes it simple to handle these requests.

Example: Basic AJAX GET Request

$.ajax({
  url: 'http://localhost:8080/api/v1/products',
  method: 'GET',
  success: function (response) {
    console.log('Data fetched successfully:', response);
  },
  error: function (error) {
    console.error('Error fetching data:', error);
  }
});

Enter fullscreen mode Exit fullscreen mode

2. HTML Setup: A simple structure to display products dynamically and support CRUD actions.

Example: Shopping Cart Table

<table id="product-table">
  <thead>
    <tr>
      <th>Product ID</th>
      <th>Product Name</th>
      <th>Price</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody id="product-list">
    <!-- Products will be appended here dynamically -->
  </tbody>
</table>

Enter fullscreen mode Exit fullscreen mode

3. Reusable AJAX Functionality: Centralizing AJAX logic helps avoid redundancy and keeps the code maintainable.

Example: Generalized AJAX Function

function ajaxRequest(url, method, data, callback) {
  $.ajax({
    url: 'http://localhost:8080/api/v1/products',
    method: 'GET',
    data: JSON.stringify(data),
    contentType: 'application/json',
    success: function (response) {
      callback(response);
    },
    error: function (error) {
      console.error('Error:', error);
    }
  });
}

Enter fullscreen mode Exit fullscreen mode

Usage Example:

ajaxRequest('http://localhost:8080/api/v1/products', 'GET', null, function (response) {
  console.log(response);
});

Enter fullscreen mode Exit fullscreen mode

4. CRUD Operations: Implement the core operations: Create, Read, Update, Delete.

Create:

$('#add-product-form').submit(function (e) {
  e.preventDefault();
  const product = {
    name: $('#product-name').val(),
    price: $('#product-price').val()
  };
  ajaxRequest('http://localhost:8080/api/v1/products', 'POST', product, function () {
    alert('Product added successfully!');
    loadProducts(); // Reload the product list
  });
});

Enter fullscreen mode Exit fullscreen mode

Read:

function loadProducts() {
  ajaxRequest('http://localhost:8080/api/v1/products', 'GET', null, function (response) {
    const productList = response.map(product => `
      <tr>
        <td>${product.id}</td>
        <td>${product.name}</td>
        <td>${product.price}</td>
        <td>
          <button class="edit-btn" data-id="${product.id}">Edit</button>
          <button class="delete-btn" data-id="${product.id}">Delete</button>
        </td>
      </tr>
    `).join('');
    $('#product-list').html(productList);
  });
}

loadProducts();

Enter fullscreen mode Exit fullscreen mode

Update:

$(document).on('click', '.edit-btn', function () {
  const id = $(this).data('id');
  const updatedProduct = {
    name: prompt('Enter new name:'),
    price: prompt('Enter new price:')
  };
  ajaxRequest(`http://localhost:8080/api/v1/products/${id}`, 'PUT', updatedProduct, function () {
    alert('Product updated successfully!');
    loadProducts();
  });
});

Enter fullscreen mode Exit fullscreen mode

Delete:

$(document).on('click', '.delete-btn', function () {
  const id = $(this).data('id');
  ajaxRequest(`http://localhost:8080/api/v1/products/${id}`, 'DELETE', null, function () {
    alert('Product deleted successfully!');
    loadProducts();
  });
});

Enter fullscreen mode Exit fullscreen mode

5. Error Handling: Handle errors gracefully to provide feedback and debugging insights.

Example: Adding User Feedback

function showError(message) {
  $('#error-message').text(message).show();
  setTimeout(() => $('#error-message').hide(), 3000);
}

// Enhanced AJAX Request with Error Feedback
ajaxRequest('http://localhost:8080/api/v1/products', 'GET', null, function (response) {
  console.log('Products loaded');
}, function (error) {
  showError('Failed to load products. Please try again.');
});

Enter fullscreen mode Exit fullscreen mode

Key Insights

  • Dynamic Updates: Real-time interactions improve user experience by eliminating the need for page reloads.

  • Efficient Code Design: The use of a centralized ajaxRequest() function ensures modularity and reusability, reducing redundancy in code.

  • Backend Integration: Interfacing with a REST API demonstrates how frontend and backend components collaborate to deliver seamless functionality.

Conclusion

By the end of this guide, you will have gained a solid understanding of how to integrate frontend applications with APIs using jQuery. Creating a functional Shopping Cart CRUD Application with a clean, efficient, and reusable codebase.
This knowledge is essential for building responsive and interactive web applications, giving you the tools to bridge the gap between user interfaces and backend APIs effectively.
With this skillset, you’re better equipped to tackle real-world development challenges, even with other languages to create a modern web solutions that delight users and exceed expectations.

Don’t forget to follow me for more tips and share your feedback below! 🚀

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay