I have been staring at this SE post on deleting using ajax and it's just not clicking.

For example, I have a plugin with a list of users. Each user has a delete icon next to it.


<td class="thin"><a class="delete delete-usericon" title="Delete" role="button" data-id="{{user.id}}" data-name={{user.name}}></a></td>

To get my javascript, I am using the init method in my main plugin class.


if (craft->request->isCpRequeset() && craft()->userSession->isLoggedIn())

So far, so good.


    var data = {
        'id': event.currentTarget.dataset.id,
        'csrfToken': // this is where i'm stuck

        'type': 'post',
        'contentType': 'application/x-www-form-urlencoded; charset=utf-8',
        'cache': false,
        'url': 'path/to/deleteUser',
        'data': data,
        'dataType': 'json',
         'timeout': 5000


actionDeleteUser() {
    error_log(__FUNCTION__); // to just test im getting this far.

As you can imagine, I'm getting a 400 Bad Request The CSRF token could not be verified.

I can put a hidden text field on my users "home page" using {{getCsrfInput}} and then grab that value no problem.

If I log out my data object, I can see it's got the correct id and csrfToken but I will still get the 400.

I'm not sure how to pass the token along with the data to the controller just yet it seems.

Thank you for your time!


Well, I believe I see my error, but I'm confident there is a better way (at least I think there could be)

I wasn't passing the correct name/key.


var data = {
     'id': event.currentTarget.dataset.id,
     'CRAFT_CSRF_TOKEN': $('[name="CRAFT_CSRF_TOKEN"]).val()

I'm getting a 404 back now - great. I can figure that out. What i'm curious about is: Is there a better way?

I've put the {{getCsrfInput}} on my "home" page of my plugin that lists the users. I feel like i've just done a nice hack-job on my plugin.

1 Answer 1


Here's how you can pass in the CSRF token via JavaScript: http://buildwithcraft.com/help/csrf-protection#updating-your-javascript

  • HOW DID I NOT FIND THIS!? Thank you!!
    – Damon
    Commented Apr 17, 2015 at 22:54

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.