Move the JSON data storage from client-side localStorage to server-side storage

I need some guidance on transitioning from using localStorage to a server-side .json file for my inventory database system. SQL is not an option for this project, so I am looking to implement it using Javascript or jQuery. Despite searching online, I have yet to find any useful examples.

While JSON seems straightforward, I'm facing some challenges in this particular scenario. Fortunately, I have access to a hosted server where I can run the necessary code.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory System</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Inventory System</h1>
        <form id="inventoryForm">
            <input type="text" id="itemOwner" placeholder="Technician's Name" required>
            <input type="text" id="itemName" placeholder="Item Name" required>
            <input type="number" id="itemQuantity" placeholder="Quantity" required>
            <input type="number" id="itemPrice" placeholder="Price" required>
            <button type="submit">Add Item</button>
        </form>
        <table id="inventoryTable">
            <tr>
                <th>Owner</th>
                <th>Item Name</th>
                <th>Quantity</th>
                <th>Price</th>
                <th></th>
            </tr>
        </table>
    </div>
    <script src="script.js"></script>
</body>
</html>

JAVASCRIPT

document.addEventListener("DOMContentLoaded", () => {
    const form = document.getElementById("inventoryForm");
    const table = document.getElementById("inventoryTable");
    const items = JSON.parse(localStorage.getItem("inventoryItems")) || [];

    // Function to update and display the inventory table
    function updateInventoryTable() {
        table.innerHTML = `
            <tr>
                <th>Owner</th>
                <th>Item Name</th>
                <th>Quantity</th>
                <th>Price</th>
                <th></th>
            </tr>
        `;

        items.forEach((item, index) => {
            const row = document.createElement("tr");
            row.innerHTML = `
                <td>${item.owner}</td>
                <td>${item.name}</td>
                <td>${item.quantity}</td>
                <td>${item.price}</td>
                <td>
                    <button onclick="editItem(${index})">Edit</button>
                    <button onclick="deleteItem(${index})">Delete</button>
                </td>
            `;
            table.appendChild(row);
        });
    }

    // Function to add a new item to the inventory
    function addItem(owner, name, quantity, price) {
        items.push({owner, name, quantity, price });
        localStorage.setItem("inventoryItems", JSON.stringify(items));
        updateInventoryTable();
    }

    // Function to delete an item from the inventory
    function deleteItem(index) {
        items.splice(index, 1);
        localStorage.setItem("inventoryItems", JSON.stringify(items));
        updateInventoryTable();
    }

    // Function to handle form submission and add new items
    form.addEventListener("submit", (e) => {
        e.preventDefault();
        const itemOwner = document.getElementById("itemOwner").value;
        const itemName = document.getElementById("itemName").value;
        const itemQuantity = document.getElementById("itemQuantity").value;
         const itemPrice = document.getElementById("itemPrice").value;
        addItem(itemOwner, itemName, itemQuantity, itemPrice);
        form.reset();
    });

    // Function to edit an existing item in the inventory
    window.editItem = (index) => {
        const newOwner = prompt("Enter the new owner's name:");
        const newName = prompt("Enter the new item name:");
        const newQuantity = prompt("Enter the new quantity:");
        const newPrice = prompt("Enter the new price:");
        if (newOwner && newName && newQuantity && newPrice) {
            items[index].owner = newOwner;
            items[index].name = newName;
            items[index].quantity = newQuantity;
            items[index].price = newPrice;
            localStorage.setItem("inventoryItems", JSON.stringify(items));
            updateInventoryTable();
        }
    };

    // Function to delete an item from the inventory
    window.deleteItem = (index) => {
        if (confirm("Are you sure you want to delete this item?")) {
            deleteItem(index);
        }
    };

    // Initialize the inventory table
    updateInventoryTable();
});

Answer №1

  1. Revamp your domContentLoaded function into a named function that accepts items as an argument. Omit the line responsible for loading items from localStorage.

  2. In the now-empty domContentLoaded function, initiate a fetch and invoke the new named function within a .then block. Keep in mind that the handling of the response depends on the structure of the json data. Let's assume it's an array.

function processInventoryItems(items) {
    const form = document.getElementById("inventoryForm");
    const table = document.getElementById("inventoryTable");

    // Function to update and display the inventory table
    function updateInventoryTable() {
        table.innerHTML = `
            <tr>
                <th>Owner</th>
                <th>Item Name</th>
                <th>Quantity</th>
                <th>Price</th>
                <th></th>
            </tr>
        `;

        items.forEach((item, index) => {
            const row = document.createElement("tr");
            row.innerHTML = `
                <td>${item.owner}</td>
                <td>${item.name}</td>
                <td>${item.quantity}</td>
                <td>${item.price}</td>
                <td>
                    <button onclick="editItem(${index})">Edit</button>
                    <button onclick="deleteItem(${index})">Delete</button>
                </td>
            `;
            table.appendChild(row);
        });
    }

    // Function to add a new item to the inventory
    function addItem(owner, name, quantity, price) {
        items.push({owner, name, quantity, price });
        localStorage.setItem("inventoryItems", JSON.stringify(items));
        updateInventoryTable();
    }

    // Function to delete an item from the inventory
    function deleteItem(index) {
        items.splice(index, 1);
        localStorage.setItem("inventoryItems", JSON.stringify(items));
        updateInventoryTable();
    }

    // Function to handle form submission and add new items
    form.addEventListener("submit", (e) => {
        e.preventDefault();
        const itemOwner = document.getElementById("itemOwner").value;
        const itemName = document.getElementById("itemName").value;
        const itemQuantity = document.getElementById("itemQuantity").value;
         const itemPrice = document.getElementById("itemPrice").value;
        addItem(itemOwner, itemName, itemQuantity, itemPrice);
        form.reset();
    });

    // Function to edit an existing item in the inventory
    window.editItem = (index) => {
        const newOwner = prompt("Enter the new owners name:");
        const newName = prompt("Enter the new item name:");
        const newQuantity = prompt("Enter the new quantity:");
        const newPrice = prompt("Enter the new price:");
        if (newOwner && newName && newQuantity && newPrice) {
            items[index].owner = newOwner;
            items[index].name = newName;
            items[index].quantity = newQuantity;
            items[index].price = newPrice;
            localStorage.setItem("inventoryItems", JSON.stringify(items));
            updateInventoryTable();
        }
    };

    // Function to delete an item from the inventory
    window.deleteItem = (index) => {
        if (confirm("Are you sure you want to delete this item?")) {
            deleteItem(index);
        }
    };

    // Initialize the inventory table
    updateInventoryTable();
}

document.addEventListener("DOMContentLoaded", () => {
  // You may also choose to define processInventoryItems here

  fetch(inventoryItemsJsonUrl).then(response => {
    const items = response.json();
    processInventoryItems(items);
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Vue.js and Laravel: Having trouble loading new image files, while the older ones load just fine

Currently, I am working on a project that involves Vue.js and Laravel. In this setup, Vue is located inside the resources/js directory of the Laravel project. My current issue revolves around loading an image from the resources/js/assets directory. While ...

How can we incorporate the final value in an iteration using a direction-agnostic for loop?

Implementing this solution, I aim to construct a for-loop that can operate regardless of whether the starting value is higher or lower than the ending value: function calculateRange(startVal, endVal) { var val = startVal; for (var step = val > ...

Using VueJS to switch classes on multiple cards

There is a page with multiple cards, each containing its own set of status radio buttons: ok, missing, error. The goal is to be able to change the status of individual cards without affecting others. A method was created to update the class on the @change ...

Go back to the pop-up window if an error occurs

I've implemented a modal window in front of my index page. When the model is valid, I redirect to the index view. However, when the model is not valid, I want it to stay on the modal. How can I achieve this? [HttpPost] [ValidateAntiForgeryToken] publ ...

When I clicked on the div, it triggered the loading of content from the server. Each time I

Whenever I click on the div element with ID "d1", it loads friend requests from the server into a hidden div named d2. However, if I click on it multiple times, the same result gets appended repeatedly. I attempted to address this issue by implementing the ...

What causes the unusual format of my PHP post function when it is received in NodeJS Express?

Hey everyone, I'm new to PHP and I'm working on a function that posts data to my NodeJS Express backend API. When I received the req.body, it had an extra { jsonObj :""} appended to it. {{"name":"PHP Game test",&quo ...

Retrieve the heading from a pop-up box

This jQuery tooltip allows for popups from another HTML page to be created. UPDATE: I have provided an example HERE The issue arises when trying to retrieve the title from the popup. Currently, using document.title displays the title of the current page ...

Guide on utilizing Vercel KV for storing and fetching posts from an API

Looking to optimize your API by utilizing Vercel KV for storing and retrieving posts? If you have a basic node.js express API that pulls random posts from MongoDB, the process of integrating Vercel KV can enhance performance. Initially, the API will resp ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

Guide on integrating AJAX with servlets and JSP for database-driven applications

What is the best way to integrate AJAX technology with servlets and JSP for a database application? I am currently developing a JSP page that makes calls to JavaScript. The JavaScript then calls a servlet where the database is accessed. How can I pass th ...

Generating HTML tags on-the-fly in Angular 2

Is it possible to generate an HTML tag dynamically within a component's template? For example: template:`<{{custom_tag}} [info]="info"></{{custom_tag}}>` ... this.custom_tag="example"; this.info={}; The resulting HTML would look like th ...

What possible problem could cause the error: an invalid character '-' appearing after a top-level value?

Utilizing the go-jmespath Golang library for querying a json file, my code is structured as follows: package main import ( "encoding/json" "log" "github.com/jmespath/go-jmespath" ) func main() { var jsonBlob = []byte(`[ { "o ...

Unable to open a modal in Angular UI after closing the initial modal

Hey there! I've been attempting to open a modal after closing the first one, but I'm encountering an issue where the second modal appears to be opened but is actually not. I'm struggling to understand what's causing this problem. Could ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

Template does not display data from Angular Service even though it has been passed through the service

After setting up an API Backend using Django, I attempted to display the data in an Angular Component to create a list of all retrieved datasets. I managed to run a test in service.spec.ts and confirmed that the data is successfully fetched from the backe ...

Storing a numpy array in a JSON file

Trying to save a numpy array into a JSON format poses a challenge due to the fact that ndarrays are not directly serializable. To workaround this, I have been converting them into lists, but this approach is consuming an excessive amount of memory. Are t ...

Form submission is failing due to a single checkbox not being submitted and an error is occurring with MultiValueDictKeyError during

<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group" ...

tips for accessing the output of a function within an object using TypeScript

I have developed a TypeScript module that simplifies the process. This function takes an object as input and executes all the functions while updating the values of the corresponding properties. If any property in the object is not a function, it will be ...

Zoom in and out on a WebGL canvas created using Three.js using the mouse scroll wheel

Currently delving into the world of WebGL (Three.js) to explore the possibilities of rendering 3D scenes within an Angular app. One challenge I'm facing is finding a way to make the mousewheel events zoom in and out of the canvas specifically, rather ...