6

I'm trying to delete items through the frontend with ajax. It's working now but want to be sure if this is a safe method:

$(".delete-file").click(function(){
    var data = {
        entryId: $(this).attr("data-id"), 
    };

    data[window.csrfTokenName] = window.csrfTokenValue; // Append CSRF Token

    $.ajax({
        context: this,
        type: "post",
        dataType: "json",
        data: data,
        url: "/actions/entries/deleteEntry",
        success: function(data, response){
            $(this).parents('.account-item').remove();
            console.log("success", response, data);
        }
    });
});
  • This works brilliantly. Now to add the confirmation pop-up. – CreateSean Aug 24 '17 at 19:57
5

That looks perfect!

Obviously this code doesn't prompt the user to confirm deletion, but that can easily be added. (Or perhaps you stripped that out of your example.)

You are specifically doing two things right here:

  • Hitting deleteEntry directly. This ensures that Craft follows all of its necessary internal procedures to properly delete the entry (and kill any relationships it may have).
  • Including the CSRF token information. Not sure if it's currently required for hitting a native Craft method, but it certainly will be when Craft 3 rolls out. Good future-proofing!

Looks great Johannes, go for it!

|improve this answer|||||
  • It's just a prototype. Don't want an annoying confirm prompt. – Johannes Lamers Mar 20 '15 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.