How to send a form delete request with Node/Express and AJAX?

Viewed 14320

I'm trying to build a REST API with NodeJs and Express (I'm a very beginner in programming), the CRUD requests work fine in Postman, but now I don't know how to send a DELETE request through a form with AJAX. I just want insert an id the text input and submit it to the server to delete a document in MongoDB. I searched everywhere but I could not understand how to perform this.

App.js

app.delete('/delete/:id', (req, res) => {
  let id = req.params.id;
  if (!ObjectID.isValid(id)) {
    return res.status(400).send();
  }
  Blog.findByIdAndRemove(id).then((docs) => {
    res.status(200).send({docs})
  }).catch((e) => {
    res.status(400)
  });
});

HTML

                                                   <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Titolo</title>
  </head>
  <body>
    <form action='/delete/:id' method="POST">
      <input id="id" type="text" name="id" /><br />
      <button id:"cancella" type="submit">Submit</button>
    </form>

    <script src="/js/jquery.js"></script>
    <script src="/js/script.js"></script>
  </body>
</html>

script.js

$(document).ready(function() {
 $('#cancella').on("click", function() {
  var id = $('#id').val();
  $.ajax({
   url: '/delete/:id',
   type: 'DELETE',
   data: {"id": id},
   dataType: 'json',
   success: function(data) {
    //do something
  }});
 });
});

4 Answers

Your form should have a hidden field that shows you are making a delete request like this:

<html>
<head>
<meta charset="utf-8">
<title>Titolo</title>
</head>
  <body>
<form action='/delete/:id' method="POST">
  <input type="hidden" name="_method" value="PUT"/>
  <input id="id" type="text" name="id" /><br />
  <button id:"cancella" type="submit">Submit</button>
</form>

<script src="/js/jquery.js"></script>
<script src="/js/script.js"></script>
</body>
</html>

Using /delete should no longer be necessary if you are sending a delete request since it is redundant.

If You want to send DELETE request by submitting the form through Ajax to App.js file, First Build Html form, build ajax script and at the last build a route at app.js file that listen to your Delete Request.Do Like This ..

In HTML

<form class="delete-form">
    <input id="id" type="text" name="id" /><br />
    <button type="submit" name="submit">Submit</button>
  </form>

In Script.js

$(document).ready(function() {
      $('.delete-form').on("click", function(e) {
          e.preventDefault();
          var id = $('#id').val();
          $.ajax({
              type: 'DELETE',
              url: '/delete/' + id,
              success: (data) => {
                console.log(data);
              },
              error: (err) => {
                console.log(error);
              });
          });
      });

App.js

app.delete('/delete/:id', (req, res) => {
  let id = req.params.id;
  if (!ObjectID.isValid(id)) {
    return res.status(400).send();
  }
  Blog.findByIdAndRemove(id).then((docs) => {
    res.status(200).send({
      docs
    })
  }).catch((e) => {
    res.status(400)
  });
});

**action='/delete/:thisIsDynamicId'**

You can also use this in html. It works correctly, the action of the form has to pass a dynamic id.

<html>
      <head>
        <meta charset="utf-8">
        <title>Titolo</title>
      </head>
      <body>
        <form action='/delete/:thisIsDynamicId' method="POST">
          <button id:"cancella" type="submit">Submit</button>
        </form>
    
        <script src="/js/jquery.js"></script>
        <script src="/js/script.js"></script>
      </body>
    </html>
Related