Reputation: 51
i want to know is there anyway to send a put request to backend on a button click in ejs ? i my case I want to just send a 'id' to the backend so that through that id i can update my data in database. also, is it necessary to use form every time to send post/get request to the server in ejs? or is there any other possible way to do so?
code snippet for some idea :
ejs:
<% if(user[i].complaint_type === "Bin Full"){ %>
<form action="/assignCol" method="POST">
<button
name="id"
value="<% user[i].id %>"
type="submit"
class="btn btn-info"
style="margin-left: 630px;"
>
Assign collector
</button>
</form>
can I do like this?
Upvotes: 1
Views: 3228
Reputation: 219
In order to achieve this you will need to use an npm module called "method-override
". So first install method-override
npm module:
npm i method-ovverride
Now in your app.js or server.js add the following to configure method-override as a middleware:
const methodOverride = require('method-override');
app.use(methodOverride());
now you need to mention in your form in ejs that this will take the data to PUT route like this:
<form action="/assignCol?_method=PUT" method="POST">
<button
name="id"
value="<% user[i].id %>"
type="submit"
class="btn btn-info"
style="margin-left: 630px;"
>
Assign collector
</button>
</form>
Upvotes: 2
Reputation: 314
This issue is really common but has a very simple solution, On the frontend side, you have a function fetch
it is the same as node-fetch
in NodeJs
With javascript
, function fetch you can easily request API
with [GET, PUT, POST]
and other methods
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
you can pass many parameters with METHOD
or you can simply avoid them
for you this can easily work:
just read values from form using javascript function, put it in data JSON
variable and then use this function
fetch(url, {
method: 'PUT',
body: JSON.stringify(data)
}
Remember this is asynchronous function don't forget to use await
with it.
For better understanding go to this MDN link:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Upvotes: 4