Reputation: 295
i have a delete api, it takes in the id of the item we want to delete, each item has its unique id, how do i get the id of the item the wants to delete and pass it to my api
here is the api
app.post("/delete_product", function (req, res) {
var data = {
id: req.session.user_id,
token: req.session.token,
product_id: 4
// you need to pass in the id of the product in data.product_id
};
functions.callAPIPost(
"https:/theurl/delete_product",
data,
function (error, result) {
var response = result;
if (response.status === 400) {
console.log('ggg',response)
res.render('products', {
result: result.data
})
} else {
res.redirect('logout')
}
}
);
});
this is my ejs
<form method='post' action='/delete_product'>
<button><iclass="os-icon os-icon-trash" style='font-size: 16px; display: inline-block; vertical-align: middle; margin-right: 10px; color: #8095A0;'></i><span>Delete</span></button>
</form>
i have an array of objects, which display as items in the browser after i loop thru them, they all have their individual id, how do i get the id once a user clicks on the item delete button that call the api to delete it.
[
{
"id": 3,
"name": "work dress",
"description": "take to work dress",
"price": "2000",
"created_at": "2020-02-26T20:30:08.000Z"
},
{
"id": 4,
"name": "movie dress",
"description": "take to movie dress",
"price": "2000",
"created_at": "2020-02-26T20:30:08.000Z"
},
{
"id": 5,
"name": "home dress",
"description": "stay at home dress",
"price": "2000",
"created_at": "2020-02-26T20:30:08.000Z"
}
]
Upvotes: 0
Views: 3115
Reputation: 36
You can pass it through the POST URL and access the value in NodeJS via req.params
.
In EJS -
<form method='post'action='/delete_product/<%= product._id %>?_method=DELETE'>
In NodeJS -
app.delete("/delete_product/:id", function (req, res) {
var id_to_delete = req.params.id;
//rest of the code
});
Upvotes: 2
Reputation: 3518
You can use a hidden input
<input type='hidden' name='product_id' value='1' />
Then in your api you can pick it up in the POST data object
Upvotes: 1