Reputation: 91
Was wondering why my code below isnt working. Basically I am fetch data from my url to delete something. on delete, it should refresh. however it doesnt seem to let me do that. But what it does is delete the post if i manually refresh the page.
Works when I use Ajax method though which I don't know why.
Fetch method
const deleteBTN = document.querySelectorAll('.deleteBtn');
const update = document.querySelectorAll('.postedNote');
console.log(deleteBTN);
for (let btn of deleteBTN) {
btn.addEventListener('click', (e) => {
console.log("Delete from front end");
console.log(btn[btn])
let id = e.target.dataset.btn;
fetch('http://localhost:3000/api/notes' + '/' + id, {
method: "DELETE",
}).then(() => {
Location: reload()
})
})
}
Ajax method
$(".deleteBtn").click((e) => {
$.ajax({
type: "DELETE",
url: `http://localhost:3000/api/notes/${e.target.dataset.btn}`,
success: function () {
console.log("delete success");
},
}).done(
setTimeout(() => {
window.location.reload();
}, 500)
);
});
Upvotes: 2
Views: 13101
Reputation: 324
We can reload by using window.location.reload as already doing on ajax success.
Kindly find below as code snippet
const deleteBTN = document.querySelectorAll('.deleteBtn');
const update = document.querySelectorAll('.postedNote');
console.log(deleteBTN);
for (let btn of deleteBTN) {
btn.addEventListener('click', (e) => {
console.log("Delete from front end");
console.log(btn[btn])
let id = e.target.dataset.btn;
fetch('http://localhost:3000/api/notes' + '/' + id, {
method: "DELETE",
}).then(() => {
window.location.reload();
})
})
}
Also, a few considerations below The use of Ajax is defeated here as we are reloading the page. Either
Or,
Upvotes: 2
Reputation: 37
I think you should'nt try to reload the page when removing one of the elements, instead I would have checked the response status and manually update the DOM to make the deleted element disappear if response says it was removed successfully.
Upvotes: 0