How to add data to a Rails ajax request

516 Views Asked by At

Is it possible to use data with Rails.ajax in a Rails 5.1+ (without jQuery) app while making a GET request? Or data work only with POSTs?

I have the following

Rails.ajax
      url: "/pages?title=lorem}"
      type: 'GET'

And I'd rather having

Rails.ajax
      url: 'pages'
      type: 'GET'
      data: { title: 'lorem' }

But when I try my params look like { "object Object"=>nil, "controller"=>"pages", "action"=>"index"}

Adding dataType: 'json' nor dataType: 'text' seem to change the params passed to the controller.

1

There are 1 best solutions below

1
On

It's possible to use data with a GET request; however, Rails.ajax simply appends the data to the url.

if options.type is 'GET' and options.data
  if options.url.indexOf('?') < 0
    options.url += '?' + options.data
  else
    options.url += '&' + options.data

Other than readability, there doesn't look to be an advantage in using the data option. Your first technique of appending the data to the url yourself is doing the same thing as Rails.ajax under the hood.

Rails.ajax
  url: "/pages?title=lorem"
  type: 'GET'

However, this is similar to how Rails.ajax handles data for POST requests as well. It doesn't perform any transformation on the data. The data is passed through untouched to the XMLHttpRequest. Data is sent like this with options.data passed through as-is.

xhr.send(options.data)