3

Hello — been reading up on how to do this and there are some posts for Craft 2, 3 — but I'm not sure what's out there works for Craft CMS 4. I am using the following JS to delete an entry. However I get an error in the console log that http://website.com/actions/entries/deleteEntry can't be found. What am I doing wrong?

<script>
    
$('#delete-entry').click(function() {
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";

    var data = {
        entryId: '{{entry.id}}',
        csrfTokenName: csrfTokenValue,
    };
    

  $.post('/actions/entries/deleteEntry', data, function(response) {
      console.log('clickResponse', response);
    }, 'json');

});
</script>

2 Answers 2

2

The delete action has moved to the ElementsController class in Craft 4, specifically:
https://github.com/craftcms/cms/blob/7d3351996c5f9f09ea59c0a712df09fc877b753f/src/controllers/ElementsController.php#L966-L1005

Updating your code as follows should work.

    var data = {
        elementId: '{{entry.id}}',
        csrfTokenName: csrfTokenValue,
    };

    $.post('/actions/elements/delete', data, function(response) {
        console.log('clickResponse', response);
    }, 'json');
1
  • Amazing thank you! — pointed me in the right direction!
    – Adrian
    Commented Jul 28, 2022 at 15:19
2

Thanks to @Ben and folks on Discord — here is some form code that also works:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    {{ actionInput('elements/delete') }}
    {{ redirectInput('/dashboard') }}
    {{ hiddenInput('elementId', entry.id) }}
    <button value="delete" type="submit">Delete</button>
</form>

Here is a version that uses JS:

Link to delete:

<a href="#" id="delete-entry-{{entry.id}}" onclick="deleteEntry('{{entry.id}}','{{entry.title}}')">Delete Entry</a>

JS Code:

<script>
    function deleteEntry(entryId,entryTitle) {
        var data = {
            elementId: entryId,
            sectionId: 1,
            {{ craft.app.config.general.csrfTokenName|e('js') }}: '{{ craft.app.request.csrfToken|e('js') }}',
        };
        let confirmAction = confirm("Are you sure you want to delete the job titled '"+entryTitle+"'");
        if (confirmAction) {
            $.post('actions/elements/delete', data, function(response) {
                console.log('clickResponse', response);
                window.location.reload();
            }, 'json')
        } else {
            //Action Canceled.          
        }
    }
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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