Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

JSONBION.IO API for update

$
0
0

I created three pages of createUser.js, UpdateUser.js, and readUser.js and index.html which simply collects user details of employees and store them. I used the create file, it worked and created a json data. I used the readUser file and it worked to read uses. I even added more user details manually so i can read the json file. But the updateUser is overrriding the json data inside my bin and adding the new user details.

I have read the documentation of jsonbin and I still cant find whta am doing wrong.

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>User Details Form</title><style>        /* Add your CSS styles here */</style></head><body><h1>User Details Form</h1><form id="userForm"><label for="firstName">First Name:</label><input type="text" id="firstName" name="firstName" required><br><label for="lastName">Last Name:</label><input type="text" id="lastName" name="lastName" required><br><label for="age">Age:</label><input type="number" id="age" name="age" required><br><label for="yearOfEmployment">Year of Employment:</label><input type="number" id="yearOfEmployment" name="yearOfEmployment" required><br><label for="hobbies">Hobbies:</label><br><input type="checkbox" id="reading" name="hobbies" value="Reading"><label for="reading">Reading</label><br><input type="checkbox" id="cooking" name="hobbies" value="Cooking"><label for="cooking">Cooking</label><br><input type="checkbox" id="hiking" name="hobbies" value="Hiking"><label for="hiking">Hiking</label><br><br><!-- Address section --><label for="street">Street:</label><input type="text" id="street" name="street" required><br><label for="city">City:</label><input type="text" id="city" name="city" required><br><label for="country">Country:</label><input type="text" id="country" name="country" required><br><button type="submit">Submit</button></form><!--<script src="jsonbin.js"></script>--><script src="jsonbin2.js"></script></body></html>
document.addEventListener('DOMContentLoaded', function() {    const form = document.getElementById('userForm');    form.addEventListener('submit', async function(event) {        event.preventDefault(); // Prevent default form submission        // Get form values        const firstName = document.getElementById('firstName').value;        const lastName = document.getElementById('lastName').value;        const age = document.getElementById('age').value;        const yearOfEmployment = document.getElementById('yearOfEmployment').value;        const hobbies = getHobbies();        const street = document.getElementById('street').value;        const city = document.getElementById('city').value;        const country = document.getElementById('country').value;        // Create user object        const newUser = {            firstName,            lastName,            age,            yearOfEmployment,            hobbies,            address: {                street,                city,                country            }        };        // Call function to update user details        await updateUserDetails(newUser);    });    // Function to get selected hobbies    function getHobbies() {        const checkboxes = document.getElementsByName('hobbies');        const selectedHobbies = [];        checkboxes.forEach(function(checkbox) {            if (checkbox.checked) {                selectedHobbies.push(checkbox.value);            }        });        return selectedHobbies;    }    // Function to update user details    async function updateUserDetails(newUser) {        const binId = 'xxaaxx'; // Replace with your bin ID        const apiUrl = `https://api.jsonbin.io/v3/b/${binId}`;        try {            // Fetch existing user data            const response = await fetch(apiUrl, {                method: 'GET',                headers: {'X-Master-Key': 'xxxxxxxx'                }            });            if (response.ok) {                const userData = await response.json();                let updatedUser;                if (userData.record) {                    const existingUser = userData.record.data;                    // Merge existing user data with new user data                    updatedUser = {                        ...existingUser,                        ...newUser                    };                } else {                    updatedUser = newUser;                }                // Update user details                await fetch(apiUrl, {                    method: 'PUT',                    headers: {'Content-Type': 'application/json','X-Master-Key': 'xxxxxxx'                    },                    body: JSON.stringify({ data: updatedUser })                });                alert('User details updated successfully now!');                form.reset(); // Clear the form after updating details            } else {                throw new Error('Failed to fetch existing user data');            }        } catch (error) {            console.error(error);            alert('Failed to update user details. Please try again later.');        }    }});

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>