Unable to Delete Record Using Jquery and Express in 'DELETE' Request

While working on my api using node/express and jquery, I encountered an issue where my DELETE requests are not functioning as expected.

JQUERY:

$('.formula-body').on('click', function (e) {
   if (e.target.className == 'fa-trash-o') {
      $.ajax({
         url: 'formula-api/' + e.target.id,
         type: 'DELETE',
         success: updateIngredient
      });
   }
});

function updateIngredient(data) {
   $('.formula-body').empty();
   var output = '';
   $.each(data, function (key, item) {
      output = `
    <tr>
      <td>${item.name}</td>
      <td>${item.amount}</td>
      <td>${item.notes}</td>
      <td><a><span id ="${key}" class="fa fa-trash-o">  </span></a></td>
    </tr>
    `;
      $('tbody').append(output);
   });
};

HTML:

<div class="centered">
<h2>Your Formula</h2>
  <table class="centered-block pure-table pure-table-striped formula-table">
    <thead class="thead-styled">
      <tr class="centered">
          <th>Ingredient</th>
          <th>Amount</th>
          <th>Notes</th>
          <th></th>
      </tr>
    </thead>
    <tbody class="formula-body">
    </tbody>
  </table>

This is how I've set up the routing in express to handle the DELETE request.

ROUTES:

var app = require('express');
var router = app.Router();
var formulas = require('../data/formula.json');

router.get('/formula-api', function(req, res){
  res.json(formulas);
});

router.post('/formula-api', function(req, res){
  formulas.push(req.body);
  res.json(formulas);
});

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  formulas.push(req.body);
  res.json(formulas);
});

module.exports = router;

Although the POST and GET requests are functioning properly, I am unable to figure out why the DELETE request is not. The console does not show any errors.

I have already imported the body-parser utility into app.js, so that should not be causing the problem.

The main concept behind this is to add a new row to the table each time a form is submitted.

The visual representation of the page can be seen here: https://i.stack.imgur.com/rcbkx.png

The objective is for the trash can icon to delete the respective row when clicked, but currently it is non-functional.

Answer №1

After some troubleshooting, I was able to solve the issue with my code. Here were the two main problems I encountered:

1). When clicking on the icon, I wasn't actually grabbing it because I needed to include both font-awesome selectors in the $('Grab Element') statement in jQuery.

2). In the routes section, I had a line that was causing issues:

formulas.push(req.body)

This line was adding an empty object back into my JSON array, which was incorrect.

To fix these errors, I made the following changes:

CHANGE 1:

if (e.target.className == 'fa-trash-o') {

was changed to:

if (e.target.className == 'fa fa-trash-o') {

I'm not sure why I couldn't just use one class as a selector, but it seems to be specific to Font Awesome. If I'm mistaken, I would appreciate any corrections.

CHANGE 2:

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  formulas.push(req.body);
  res.json(formulas);
});

was changed to:

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  res.json(formulas);
});

These adjustments solved the problem and everything is working smoothly now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a production build of a React app on a high-end machine is taking an unexpectedly

Our team is facing challenges with the performance of our production build, as it is taking approximately 20 minutes to complete. We initially suspected that the issue might be related to our local machine's capabilities, so we decided to run the buil ...

Manipulating arrays in a JSON file with JavaScript

Struggling with adding a new value to an array stored in a file.json? The array currently contains ["number1", "number2"], and you want to add "number3". However, attempts to define a variable in the JavaScript file containi ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Quick tutorial on extracting an array of objects in Node.js

I need assistance with creating a simple todo app using React JS and Node. How can I fetch an object array (task list) from Node to React in order to display that list when a button is clicked? const lists =[ {toDo: "learn react"} ] app.post(&apos ...

The ongoing battle for routing supremacy between Express and Nginx

My current setup involves a unique configuration that I'll need to maintain until I have the opportunity to refactor the project later this year. Right now, it's a static index.html landing page being served with a root location "/" by NGINX. I& ...

Employing ajax verification to ensure that the email address does not already exist prior to the main POST request (ASP.NET MVC4)

I used to have the ability to submit an asynchronous call to a method that checked for a username in the database and returned it as JSON while the user was typing. However, I can't seem to locate the tutorial that explained how to do this. Currently, ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...

In what way can I fill out my search fields using the criteria included in the URL?

In the process of developing an asp.net web application, I have implemented a code snippet to construct a section for search fields. This code builds URL parameters based on user input: <script type="text/javascript> $(document).ready(function(){ ...

transmitting various data with ajax requests

I need assistance in sending the data stored in the variable named "blog_id" to the page called "blog_img_upload.php", along with the form_data. Here are the codes: var blog_id = "<?php echo"$blog_id"?>"; let form_data = new FormD ...

Configure the IIS HttpCompression settings to compress only JSON responses, specifically those coming from asynchronous JavaScript and

I've been tinkering with the "applicationHost.config" file located in the directory "C:\Windows\System32\inetsrv\config." Everything seems to be going smoothly, but I just want to confirm something: <httpCompression directory=" ...

Having trouble with dynamic import and vitest?

I'm currently using Vitest to conduct tests on a Node.js + Express API. I've encountered an issue with my routes: I consistently receive a 404 error on the initial test run, but subsequent runs return a status code of 200. Has anyone else faced ...

Webpack fails to transmit watchOptions to the watcher

Having an issue with webpack and wondering if fixing it will require forking the repo. Also, seeking guidance on merging it back in. The problem arises when using the webpack npm module environment in a development virtual machine where code is edited on ...

Here is a guide on how to ensure that the div elements automatically fill the available space

Looking at this html page: Check out the jsFidlle Demo here I am aiming to have the boxes fill up the space effortlessly, each with equal width but varying heights. This is similar to the layout in Google Keep notes ...

Is it possible for the upload form submission to wait until the file processing is finished?

Is it possible for the form submission to wait until the file processing is complete? I am currently using web2py and its sqlform to upload a video file. As the file is being uploaded, it is also being converted to flv format. The progress of both uploadi ...

Verify if two strings match using HBS (handlebars-express)

I am attempting to compare two different Strings using HBS. The function appears as follows: hbs.registerHelper('if_equal', function(a, b, opts) { if (a == b) { return opts.fn(this) } else { return opts.inverse(this) ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

Animation glitches occurred following the update to Android Jelly Bean, appearing as duplicated animations on

I am currently working on developing an HTML5 app for Android using JQuery 1.1.0 and Phonegap 1.9.0. The app includes a small animation of a battery being drawn on the canvas and updating dynamically. This animation functioned perfectly on Android 4.0.4. ...

Updating a mongoose model with an array of objects: A step-by-step guide

Could you provide insight on how to modify the likes array using Mongoose? var postSchema = new mongoose.Schema({ author: String, content: String, date: String, likes: [{theID: String}], numDate: Number }); var UserSchema = mongoose.S ...

Tips for fixing the problem (testcafe-live not functioning) in testcafe version 0.21.0

Recently, following an upgrade from testcafe version 0.21 to 0.23, we ran into an issue where testcafe-live stopped functioning properly. Here is the command we are using: testcafe-live chrome tests/menu/test0001.ts --screenshots my-fixture/chrome --trac ...

Having trouble loading items in a <select> tag with Jquery?

Dealing with a seemingly simple issue, I am struggling to figure out how to load items into a select using jQuery. Working with the Materialize theme available at: The code snippet in question: <div class="input-field col s12"> <s ...