5

I am sending some very simple ajax post and patch requests via javascript in my application. The functionality is fine, works as intended. However, I do not see the authenticity token in the ajax request params and it still works.

javascript (jQuery)

$.ajax({
  type:'PATCH', 
  url: '/dashboard/goals/#{@goal.id}.js', 
  data: $.param({ 
    new_invitation: { 
      recipient_id: recId, 
      type: "GoalInvite", 
      user_id : #{current_user.id}
    }
  })
}); 

and the params appear as follows in the log -

Parameters: {"new_invitation"=>{"recipient_id"=>"24", "type"=>"GoalInvite", "user_id"=>"23"}, "id"=>"234"}

no authenticity token. I think I know how I could add it in, but I am surprised that it even works without it. Can anyone shed some light on this?

Community
  • 1
  • 1
Matt Ramirez
  • 673
  • 6
  • 19

1 Answers1

13

If you inspect the request object you'll (hopefully) see that there's a request header named HTTP_X_CSRF_TOKEN that contains the authenticity token. The jquery_ujs library takes care of this for you so you dont have to include the token in AJAX requests manually.

Arctodus
  • 5,743
  • 3
  • 32
  • 44
  • yep the header was `X-CSRF-Token:` – Matt Ramirez Jun 18 '14 at 14:16
  • 1
    It worked! after putting the line `= require jquery_ujs` in the `application.js` file. Thank you. – yeyo Dec 30 '14 at 03:24
  • +1 for reminding me that the jquery_ujs library does this for me. I was working on an external/client facing side of the app and didn't have this included, and couldn't figure out why only this particular ajax request was complaining about the auth token. Thanks! – Greg Blass Nov 15 '17 at 16:32