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',
})
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();
}
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;
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 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);
});
Hello after setup a simple async function with promise return i'd like to use then promise instead of try!
But is returning
await is a reserved word
for the second await in the function.
i've tried to place async return promise the data! but did not worked either
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await is a reserved word (100:25)
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
^
fetch("/notifications/mark_as_read", {
You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.
const makeRequest = async (url, options, auth_token) => {
try {
// Default options and request method
if (!options) options = {}
options.method = options.method || 'GET'
// always pass a body through, handle the payload here
if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
options.body = JSON.stringify(options.body)
} else if (options.body) {
url = appendQueryString(url, options.body)
delete options.body
}
// setup headers
if (!options.headers) options.headers = {}
const headers = new Headers()
for(const key of Object.keys(options.headers)) {
headers.append(key, (options.headers as any)[key])
}
if (auth_token) {
headers.append('Access', auth_token)
}
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json')
options.headers = headers
const response = await fetch(url, options as any)
const json = await response.json()
if (!response.ok) {
throw json
}
return json
} catch (e) {
console.error(e)
throw e
}
}
appendQueryString is a little helper util to do the get qs params in the url
const appendQueryString = (urlPath, params) => {
const searchParams = new URLSearchParams()
for (const key of Object.keys(params)) {
searchParams.append(key, params[key])
}
return `${urlPath}?${searchParams.toString()}`
}
Now, to get to how you update your code, you'll notice things become less verbose and more extensive.
async infiniteNotification(page = 1) {
try {
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
const data = await makeRequest(
`/notifications`,
{ body: { page } },
auth_token
)
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
const markedAsReadResponse = makeRequest(
"/notifications/mark_as_read",
{
method: "POST",
body: {
notification: { read: true }
},
auth_token
)
this.props.changeNotifications();
} catch (e) {
// TODO handle your errors
}
}