1

My goal is to have an onclick function send a post request to delete an HTML li off the page. The post request uses a mongoose function to delete the data then I want the page to be reloaded so the user sees the new page without the item they deleted. The deletion works fine however I have to refresh the page to see it be deleted. There isn't any error messages.

garage.jade

doctype html 
html(lang='en')
  head  
    script 
       include ../Scripts/garage_scripts.js 
    
  body 
    h1 Welcome to The Garage
      h2= title
      ul
      - for (let i=0; i<list_o_cars.length; i++)
        li(onclick='delete_car(this)', id="cars")= list_o_cars[i]

garage_scripts.js

function delete_car(target) {
  const data = {
    car: target.innerHTML,
  };

  const url = "http://localhost:3000/car_module/delete";
  let request_param = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(data),
  };

  fetch(url, request_param);
}

controller.js

exports.delete = function (req, res, next) {
res.send("hi") 
[enter image description here][1]//this would be a render but I am just testing to see if it will reload or redirect to a new page

this is the image of the request preview img

Kristian
  • 2,456
  • 8
  • 23
  • 23
MMerlinn
  • 13
  • 2
  • The page is not going to re-render by itself. You either have to reload the page manually with javascript (probably not a good approach) or delete the ```li``` with javascript and when the user eventually reloads the page the data will be gone. – lnogueir Mar 11 '21 at 23:54
  • What are you trying to do after sending response "res.send('hi') ? – Masood Mar 11 '21 at 23:57

2 Answers2

0

Maybe just add window.location.reload(); after fetch(). Someone did a much better job of explaining this than I am, HERE

Duncan
  • 1
0

Since fetch returns a promise, you can resolve it with .then() and reload the page.

fetch(url, request_param).then(function(res) { 
    window.location.reload();
}).catch(function(error) {
    console.log(error);
});
Masood
  • 1,545
  • 1
  • 19
  • 30