1

I created an app that adds and removes 'Case Studies'. I am able to add entries easily, but when I try to delete an entry, I am redirected of the form page with the form action URL appended to the end. The entry does in fact get deleted when I go back to the original form page, but ideally I'd like to be able to stay on the same page as I add/delete entries.

form.jade

form(method="POST", action="/form/#{entry._id}?_method=DELETE")
    input(type="submit", value="Delete")

form.js

/* Delete Case Study */
router.delete('/:id', function (req, res) {
  Entry.findById(req.params.id)
    .exec(function(err, entries) {
       // changed `if (err || !doc)` to `if (err || !entries)`
        if (err || !entries) {
            res.statusCode = 404;
            res.send({});
        } else {
            entries.remove(function(err) {
                if (err) {
                    res.statusCode = 403;
                    res.send(err);
                } else {
                    res.send('Deleted entry with link: ', entries.link);
                }
            });
        }
    });
});

Here is a link to my app on Heroku, as well as my GitHub repo:

https://hidden-wave-1121.herokuapp.com/form

https://github.com/hlmurray/express-app

Any help here would be great, thank you!

hannah
  • 130
  • 2
  • 10

1 Answers1

1

You can use a javascript http request instead of a form post/submission and wire it with an onclick function on your delete button, heres a StackOverflow Question which covers http requests.

input(type="button", onclick="deleteItem({entry._id})")

function deleteItem(theID)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "DELETE", '/form/'+ theID, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

Also it looks like you'll need to update your route in form.js so that it reads /forms/:id.

That won't get rid of the HTML on your page though, so you'll need some more javascript to delete that DOM element. Usually when I work with the MEAN stack, I do all my form posts and calls using the Angular $http method, that way you don't get any page changes. I still use forms, but instead of the standard submit, I use ng-submit, which prevents page changes.

Hope that helps, let me know if I can include anything else, and I'll update the answer.

Community
  • 1
  • 1
Eric Hartmann
  • 756
  • 5
  • 12