Search code examples
jquerycssnode.jsexpressejs

How can I send put request to backend through ejs template without using form?


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?


Solution

  • 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