0

So I'm doing an ajax call to a Rails 4.2 app setup with devise like this:

    $.ajax
      url: '/some_ajax_call',
      type: 'POST',
      dataType: "json",
      beforeSend: (xhr) ->
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
      data: { yo: "yes" },
      success: (response) ->
        console.log('hello')

I end up with a params hash in the Rails controller structured like this:

{ "data" => { "yo" => "yes" } }  #params

Is there a way to do the AJAX call so that I end up with the following params hash instead (basically the params minus the data key)

{ "yo" => "yes" }  #params
Nona
  • 5,302
  • 7
  • 41
  • 79
  • 1
    You shouldn't encode the header for the CSRF yourself. Use the Rails helper to do it. Adding beforeSend: $.rails.CSRFProtection fixes the CSRF problem. See this answer: [http://stackoverflow.com/questions/37337691/rails-post-cant-verify-csrf-token-a‌​uthenticity/37337966#37337966](http://stackoverflow.com/questions/37337691/rails-post-cant-verify-csrf-token-a‌​uthenticity/37337966#37337966) – Michael Gaskill May 20 '16 at 22:27
  • @MichaelGaskill where does the `$.rails.CSRFProtection` come from? It's not part of jQuery, right? – Nona May 20 '16 at 22:47
  • It's an unobtrusive javascript (UJS) helper provided by Rails. You can find it in `rails.js` if you're looking for it in the Rails source. – Michael Gaskill May 20 '16 at 22:51

1 Answers1

1

You can pass params in the url:

 url: '/some_ajax_call?yo=yes'
Graham Slick
  • 6,692
  • 9
  • 51
  • 87