Thursday, 2 May 2019

Converting Javascript datatables to use Opal in Rails app

I am using the ajax-datatables-rails. Below is the JS for my datatable. I want to convert the javascript into equivalent Opal.rb.

jQuery(document).ready(function() {
  var table = $('#organizations-datatable');
  var token = $('meta[name=csrf-token]').attr('content');
  table.DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
      "url": "/organizations/datatable.json",
      "type": 'POST',
      "beforeSend": function (xhr) {
          xhr.setRequestHeader('X-CSRF-Token', token)
        }
    },
    "pagingType": "full_numbers",
    "destroy": true,
    "columns": [
      {"data": "name"},
      {"data": "desc"},
      {"data": "industry"},
      {"data": "tags"}
    ],
    "iDisplayLength": 25
  });
});

It includes adding the CSRF token to the ajax request for data.

I would like all of our javascript to be written as opal for readability, etc. Please don't debate that choice, I only care to understand how to get this working as Opalrb via opal/rails-ujs/opal-jquery

The below Opal does not achieve the same as the above JS. Can anyone help me understand why?

Element.expose :DataTable

Document.ready? do
  token     = Element['meta[name=csrf-token]'].attr('content');
  settings  = {
      "processing": true,
      "serverSide": true,
      "ajax": {
        "url": "/organizations/datatable.json",
        "type": 'POST',
        "beforeSend": lambda do
          xhr = `new window.XMLHttpRequest()`
          xhr.setRequestHeader('X-CSRF-Token', token)
        end 
      },
      "pagingType": "full_numbers",
      "destroy": true,
    "columns": [
      {"data": "name"},
      {"data": "desc"},
      {"data": "industry"},
      {"data": "tags"}
    ]
    }
  Element['#organizations-datatable'].DataTable(settings.to_n)

end

What am I missing here? Why isn't this Opal any good?

Edit: This is what my route for this looks like, this ensures POST works for this:

Rails.application.routes.draw do
    concern :with_datatable do
        post 'datatable', on: :collection
    end
    resources :organizations,   concerns: [:with_datatable]
end



from Converting Javascript datatables to use Opal in Rails app

No comments:

Post a Comment