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 overriding the JSON data inside my bin and adding the new user details.
I have read the documentation of jsonbin and I still can’t find what I am doing wrong.
index.html file
User Details Form /* Add your CSS styles here */User Details Form
First Name: <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>
script.js file 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.');
}
}
});
and .json file structure
{
"data": {
"firstName": "Jedidiah",
"lastName": "Onwubiko",
"age": "2222",
"yearOfEmployment": "2222",
"hobbies": [
"Reading"
],
"address": {
"street": "Sauka Kahuta Minna Niger State",
"city": "Minna",
"country": "Nigeria"
}
}
}
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 overriding the JSON data inside my bin and adding the new user details.
I have read the documentation of jsonbin and I still can’t find what I 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.');
}
}
});
{
"data": {
"firstName": "Jedidiah",
"lastName": "Onwubiko",
"age": "2222",
"yearOfEmployment": "2222",
"hobbies": [
"Reading"
],
"address": {
"street": "Sauka Kahuta Minna Niger State",
"city": "Minna",
"country": "Nigeria"
}
}
}
Above is the index. html, js and json file.
I sent them a mail and got this.
Hey Jedidiah,
I’m Vaibhav from JSONBin.io. Thank you for reaching out to us.
Apologies for the late reply. As far as your question goes, the API you are using is PUT API and not the PATCH. We haven’t released the PATCH API yet. So the idea is when you update, you need to fetch the record, modify it’s content and then update the record.
I hope the above explains. Let me know if you have any questions.
Thank you, VaibhavI 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 overriding the JSON data inside my bin and adding the new user details.
I have read the documentation of jsonbin and I still can’t find what I am doing wrong.
User Details Form /* Add your CSS styles here */User Details Form
First Name: <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>
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.');
}
}
});
{
“data”: {
“firstName”: “Jedidiah”,
“lastName”: “Onwubiko”,
“age”: “2222”,
“yearOfEmployment”: “2222”,
“hobbies”: [
“Reading”
],
“address”: {
“street”: “Sauka Kahuta Minna Niger State”,
“city”: “Minna”,
“country”: “Nigeria”
}
}
}
Above is the index. html, js and json file.
I sent them a mail and got this.
Hey Jedidiah,
I’m Vaibhav from JSONBin.io. Thank you for reaching out to us.
Apologies for the late reply. As far as your question goes, the API you are using is PUT API and not the PATCH. We haven’t released the PATCH API yet. So the idea is when you update, you need to fetch the record, modify it’s content and then update the record.
I hope the above explains. Let me know if you have any questions.
Thank you, Vaibhav
github repo: Jedidiah-Solomon/Back-end-Stacks/tree/main/JS/API/fetch-api/JSONBIN