1

I'm having trouble with using coffee on an ajax request on a change event for a select input.

My actual script works on the events:

$ ->
  $(document).ready ->
    $(document).on 'change', '#empresa_id', (evt) ->
      $.ajax '/empleados/find_branches',
        type: 'POST'
        dataType: 'json'
        data: {
          id: $("#empresa_id option:selected").val()
        }
        error: (jqXHR, textStatus, errorThrown) ->
          console.log(jqXHR)
          console.log(textStatus)
          console.log(errorThrown)
          console.log("AJAX Error: #{textStatus}")
        success: (data, textStatus, jqXHR) ->
          for key, value of data['data']
            $('#sucursales_id').append($('<option>').text(value.nombre).attr('value', value.id));

I have on application.html.erb:

<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

On application.js:

//= require rails-ujs
//= require jquery3
//= require activestorage
//= require turbolinks
//= require_tree .
//= require popper
//= require bootstrap

But i still get:

Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)

I know that //= require rails-ujs actually add the token on the header of the request but on the browser doesn't show it.

I already do rake assets:precompile.

Am i missing something?

:

Ulises
  • 406
  • 7
  • 22
  • Did you already look at [this question](https://stackoverflow.com/questions/35181340/rails-cant-verify-csrf-token-authenticity-when-making-a-post-request)? Also, out of curiosity, does `find_branches` make any changes? I wonder if it might want to be a `GET` instead of a `POST`? – jvillian Jan 17 '19 at 19:09
  • Hi, it's a post `post 'empleados/find_branches', to: 'empleados#find_branches'` – Ulises Jan 17 '19 at 19:12
  • No, I understand that it's a `POST`. My only point is that if the action is [idempotent](https://www.restapitutorial.com/lessons/idempotency.html), then it would, IMO, be more conventional to use a `GET` request. That's why I asked if `find_branches` makes any changes. – jvillian Jan 17 '19 at 19:15
  • Yes, i need it in POST, i don't know why the exception is throw becase on the require is added "rails-ujs" and it adds the token on the header. – Ulises Jan 17 '19 at 19:17

1 Answers1

2
$ ->
  $(document).ready ->
    $(document).on 'change', '#empresa_id', (evt) ->
      $.ajax '/empleados/find_branches',
        type: 'POST'
        dataType: 'json'
        beforeSend: (xhr) -> xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
        headers: {
              'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
        data: {
          id: $("#empresa_id option:selected").val()
        }
        error: (jqXHR, textStatus, errorThrown) ->
          console.log(jqXHR)
          console.log(textStatus)
          console.log(errorThrown)
          console.log("AJAX Error: #{textStatus}")
        success: (data, textStatus, jqXHR) ->
          for key, value of data['data']
            $('#sucursales_id').append($('<option>').text(value.nombre).attr('value', value.id));

Add beforeSend and headers

Boris BRESCIANI
  • 527
  • 7
  • 16