I have an issue with my javaScript code as the delete feature is working but, it is not deleting the right data ...
Example:
1 - test1
2 - test2
3 - test3
My issue is when I try to delete test1, the program deletes test3 which means the program always deletes the last data in the list.
Please, could you help?
Here's my code:
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
let theTask = [];
let text = '';
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
addNewTask();
getDataa();
};
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
}
}
xhr.send(JSON.stringify(params));
getDataa();
};
const getDataa = () => {
console.log("get Data")
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (i = 0; i <= data.ScannedCount; i++) {
let text = '';
//const items = data.Items[i].Description;
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item, index) {
theTask= data.Items[index].Description;
text += ' <button type="button" class="btn" id="task2" onclick="deleteData()"> <i class="fa fa-trash"></i> </button> '+ " " + data.Items[index].Description + "<br>";
}
}
})
.catch(function(error) {
console.log(error);
});
}
async function deleteData() {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
let taskDescription = theTask;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
window.onload = init;
let taskDescription = theTask; always gets the last value that was ever assigned to theTask. You should make the task a parameter to the deleteData() function.
text and theTask don't need to be global variables.
I'm not sure why you have the loop for (let i = 0; i <= data.ScannedCount; i++). You never use i in the loop.
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
addNewTask();
getDataa();
};
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {}
}
xhr.send(JSON.stringify(params));
getDataa();
};
const getDataa = () => {
console.log("get Data")
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (let i = 0; i <= data.ScannedCount; i++) {
let text = '';
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item) {
let theTask = item.Description;
text += ` <button type="button" class="btn" id="task2" onclick="deleteData('${theTask}')"> <i class="fa fa-trash"></i> </button> ${theTask}<br>`;
}
}
})
.catch(function(error) {
console.log(error);
});
}
async function deleteData(taskDescription) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
window.onload = init;
Related
// Function to delete the data
app.delete("/api/theTasks/:id", (req, res) => {
let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
let index = Items.indexOf(taskToRemove);
Items.splice(index, 1);
res.json(taskToRemove);
});
Please, my application is deleting my last entries instead of the
desired data. Please, could you help? unsure, how to pass the
variable in the URL? I believe I should delete the data based on the
ID which should be in the URL as a parameter but, It doesn't work for
me
const URL = "http://localhost:5050/api/theTasks/";
const init = () => {
getDataa();
document.querySelector("#newTask").addEventListener("click", addNewTask);
//addNewTask();
};
/* The method to add a task entered by the user
*/
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "http://localhost:5050/api/theTasks/";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let taskDescription = document.querySelector("#task").value;
let theTask = taskDescription;
let params = {
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {}
}
xhr.send(JSON.stringify(params));
console.log("Display the data");
getDataa();
};
/* The method to Get the data from th API
*/
const getDataa = () => {
console.log("get Data")
fetch(URL, {
method: "GET",
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S"
}
})
.then(resp => resp.json())
.then(function(Items) {
console.log(Items);
// Loop to access all rows
let text = '';
Array.from(Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item) {
let theTask = item.Description;
let taskToRemove = Items.id;
text += ` <button type="button" class="btn" id="task2" onclick="deleteData('${theTask}')"> <i class="fa fa-trash"></i> </button> ${theTask}<br>`;
}
})
.catch(function(error) {
console.log(error);
});
}
- Here's my code for my own API that I have created using the POSTMAN
API ... is there an issue with that?
<!-- begin snippet: js hide: false console: true babel: false -->
/* the method to delete the data
*/
async function deleteData(taskDescription) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
let url = "http://localhost:5050/api/theTasks/:";
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
You are already sending the taskDescription to the delete function. Now you just need to add the ID of whatever you are deleting to that same function and append it to the url of the endpoint in the fetch.
async function deleteData(taskDescription, elementID) {
console.log("deleteing data");
let xhr = new XMLHttpRequest();
//add the id here
let url = `http://localhost:5050/api/theTasks/:${elementID}`;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: JSON.stringify({
'Description': taskDescription,
'version': 'JSON',
}),
})
.then(res => res.json()).then(console.log);
console.log(taskDescription);
getDataa();
}
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
//document.querySelector("#deleteTask").addEventListener("click", deleteData);
getDataa();
};
const getDataa = () => {
addNewTask();
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (i = 0; i <= data.ScannedCount; i++) {
let text = "";
//const items = data.Items[i].Description;
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item, index) {
text += ' <button type="button" class="btn" id="task" onclick="deleteData()"><i class="fa fa-trash"></i></button>' + " " + data.Items[index].Description + "<br>";
}
}
})
.catch(function(error) {
console.log(error);
});
}
const deleteData = () => {
console.log("delete data ");
//let deleteDescription = document.querySelector("#task").value;
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: {
'StudentId': 'studentId',
'Description': 'taskDescription',
'version': 'JSON',
}
})
.then(res => {
if (res.ok) {
console.log("DELETE request successful");
getDataa();
return res
} else {
console.log("DELETE request unsuccessful");
}
return res
})
.then(res => res.json())
.then()
.catch(error => console.log(error))
}
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log("New record was added ...");
}
}
xhr.send(JSON.stringify(params));
};
window.onload = init;
Please, could you help with the delete function is not working as expected
Please, see attached file
Your code is sending an Object in the body
You're also setting the values of the properties to the literal strings 'studentId' and 'taskDescription'
The following may fix your issue
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
})
I've been working on a script that creates and updates stuff with the ExactOnline API.
when I run the script locally everything works fine but when I try to use it on a platform such as Zapier or n8n it doesn't work as intended.
on Zapier it only runs just before it does a fetch request
this my code that I use in zapier:
var token = 'token';
var divisionid = 'divisionid';
var AMRelatieData = {
"Name": "company name",
"City": "city name",
"Website": "website.com"
};
var AMContactData = {
"FirstName": "firstname",
"LastName": "lastname",
"City": "name city"
};
var testrlid;
async function actionHandeler(actionValue) {
var action = actionValue;
if (action == "cp_maken_&_relatie_maken") {
var maakRelatieWaarde = await maakRelatie(AMRelatieData);
var POSTrelatieID = maakRelatieWaarde;
AMContactData.Account = POSTrelatieID;
var maakContactwaarde = await maakContact(AMContactData);
var POSTcontactID = maakContactwaarde;
testcpid = POSTcontactID;
testrlid = POSTrelatieID;
return ('maakContactwaarde succes');
}
//functions
async function updateRelatie(updateData, relatieId) {
var UpdateRelatiePUT = await PUTreq(1, updateData, relatieId);
console.log(UpdateRelatiePUT);
return ("updateRelatie succes");
}
async function maakRelatie(createData) {
var relatieId;
console.log('maakRelatie: ');
var maakRelatiePOST = await POSTreq(1, createData);
console.log('maakRelatieFunc:' + JSON.stringify(maakRelatiePOST));
return await maakRelatiePOST.d.ID;
}
async function maakContact(createData) {
var contactId;
var maaktcontactPOST = await POSTreq(2, createData);
console.log('maaktcontactFunc:' + JSON.stringify(maaktcontactPOST));
var jsonData = {
MainContact: maaktcontactPOST.d.ID
};
var relatieIdUpdate = createData.Account;
await updateRelatie(jsonData, relatieIdUpdate);
}
async function POSTreq(type, DATA) {
console.log('postreq');
var POSTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';
if (type == 1) {
POSTendpoint += 'Accounts';
}
if (type == 2) {
POSTendpoint += 'Contacts';
}
var outputPOST;
console.log(DATA);
await fetch(POSTendpoint, {
method: "POST",
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify(DATA)
}).then(response => {
return response.json();
}).then(jsonResponse => {
var responseOut = jsonResponse;
outputPOST = responseOut;
}).catch(error => {
console.log(error);
});
return outputPOST;
}
async function PUTreq(type, DATA, id) {
var PUTendpoint = 'https://start.exactonline.nl/api/v1/'+ divisionid +'/crm/';
console.log('put data');
console.log(id);
console.log('data' + DATA);
console.log(type);
if (type == 1) {
PUTendpoint += "Accounts(guid'" + id + "')";
}
if (type == 2) {
PUTendpoint += "Contacts(guid'" + id + "')";
}
console.log(PUTendpoint);
console.log(PUTendpoint);
await fetch(PUTendpoint, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
body: JSON.stringify(DATA)
});
}
}
async function actionHandlerFunc(){
console.log("begin");
await actionHandeler("cp_maken_&_relatie_maken");
return ("done did sum stuff");
};
output = [actionHandlerFunc()]
I am currently attempting to get an image upload component built in Zapier but am having issues getting it to work. I have to be able to download an image, and then POST it to a new endpoint without storing it locally. Currently, the closest I've been able to do is get an IncomingMessage to POST, but I know that's not right.
Does anyone have any advice?
let FormData = require('form-data');
let http = require('https');
const makeDownloadStream = (url) => {
new Promise((resolve, reject) => {
http.request(url, resolve).on('error', reject).end();
});
}
const makeUploadStream = (z, bundle, options) => {
var imageRequest = options;
const promise = z.request(imageRequest);
return promise.then((response) => {
return response.data;
});
}
const addAttachment = async (z, bundle) => {
/*var request = {
'url': bundle.inputData.attachment
};
const promiseAt = z.request(request);
return promiseAt.then((stream) => {*/
const form = new FormData();
var data = `{"type": "records", "attributes": {"form_id": ${bundle.inputData.form_id}}}`
const stream = await makeDownloadStream(bundle.inputData.attachment);
form.append(`field_${bundle.inputData.field_id}`, stream);
form.append('data', data);
var request = {
'url': bundle.inputData.url,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`
},
'body': form
};
const response = await makeUploadStream(z, bundle, request);
return response;
//});
}
I figured it out myself. For anyone needing to upload an image on Zapier, here it is:
let FormData = require('form-data');
const makeDownloadStream = (z, bundle) => {
var imageRequest = {
'url': bundle.inputData.attachment,
'method': 'GET',
'raw': true
};
const promise = z.request(imageRequest);
return promise.then(async (response) => {
var buffer = await response.buffer();
return {
'content-type': response.headers.get('content-type'),
'content': buffer,
'filename': response.headers.get('content-disposition').replace('attachment; filename="', '').replace('"', '')
}
});
}
const addAttachment = async (z, bundle) => {
const form = new FormData();
const content = await makeDownloadStream(z, bundle);
form.append(`field_${bundle.inputData.field_id}`, Buffer.from(content.content.toString('binary'), 'binary'), {
filename: content.filename
});
const request = {
'url': `${bundle.inputData.url}/api/records/${bundle.inputData.record_id}`,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`,
'Content-Length': form.getLengthSync()
},
'body': form
};
const promise = z.request(request);
return promise.then((response) => {
return response.data;
});
}
I have a question about the code. Probably the solution is very simple, but I'm taking the first step in JavaScript and it is not obvious to me.
I have some backend ready, postman sending POST is ok. So backend is fine.
I wrote a simple application in which after pressing the button saves the given data in the database.
Unfortunately, this doesn't work with the debugger, everything is fine. However, by clicking the button in the view something is wrong and no fetch is called. The object is not saving to the database.
Please help.
Api = function() {
this.header = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
Api.prototype.buildUrl = function(id) {
return "http://localhost:3000/db/shop_name/" + id;
};
Api.prototype.post = function(id, data) {
const urlPost = api.buildUrl(id.value);
return fetch(urlPost, {
method: "post",
body: JSON.stringify(data),
headers: this.header
})
.then(res => res.json())
.then(res => {
console.log("Dodałem użytkownika:");
console.log(res);
})
};
Api.prototype.get = function(id) {
//const urlGet = api.buildUrl(id);
return fetch(id, {
method: "GET",
})
.then(resp => {
alert(resp.json());
return resp.json();
})
};
Api.prototype.getAlll = function() {
return fetch(url, {
method: "GET"
})
.then(resp => {
alert(resp.json());
return resp.json()
})
};
Api.prototype.update = function(id, data) {
const url = api.buildUrl(id);
return fetch(url, {
method: "PUT",
body: JSON.stringify(data)
})
.then(resp => {
return resp.json()
.catch(error => {
let notFound = "The server can not find requested resource";
document.getElementById("stars").innerHTML = notFound + error.status;
})
})
};
Api.prototype.addProduct = function(id, data) {
return this.post(id, data);
};
Api.prototype.deleteProduct = function(id) {
return this.delete(id);
};
Api.prototype.updateProduct = function(id, data) {
return this.update(id, data);
};
Api.prototype.getProduct = function(id) {
return this.get(id);
};
Api.prototype.getAllProducts = function() {
return this.getAlll;
};
const Main = function() {
this.id = document.getElementById("id");
this.addCount = document.getElementById("count");
this.addName = document.getElementById("name");
this.addPrice = document.getElementById("price");
};
Main.prototype.add = function() {
// const ido = this.id.value;
const data = {
"price": this.addPrice.value,
"name": this.addName.value,
"count": this.addCount.value,
};
// let id = api.buildUrl(this.id.value);
api.addProduct(this.id, data);
};
Main.prototype.update = function() {
const data = {
"price": this.price,
"name": this.name,
"count": this.count,
};
api.updateProduct(id, data);
};
Main.prototype.delete = function() {
let id = api.buildUrl(this.id);
api.deleteProduct(id);
};
Main.prototype.get = function() {
let id = api.buildUrl(this.id.value);
api.getProduct(id);
};
Main.prototype.getAll = function() {
api.getAllProducts();
};
const api = new Api();
const main = new Main();
let addButton = document.getElementById('postBtn');
addButton.addEventListener('click', function() {
main.add();
});
/*
addButton.addEventListener("click",main.add.bind(main));
*/
let updateButton = document.getElementById("updateBtn");
updateButton.addEventListener("click", function() {
main.update();
});
let deleteButton = document.getElementById("deleteBtn");
deleteButton.addEventListener("click", function() {
main.delete();
});
let getButton = document.getElementById("getBtn");
getButton.addEventListener("click", function() {
main.get();
});
let getAllButton = document.getElementById("getAllBtn");
getAllButton.addEventListener("click", function() {
let tst = main.getAll();
console.log(tst);
});