I am trying to migrate Rails 4.2 application to Rails 5.1. In rails 4.2 we heavily used JQuery. At the moment I am struggling to make the forms, with remote: true
attribute work properly. As an example this is a simple form where user select the country
= simple_form_for(:user_data,
url: user_path(@user),
remote: true,
method: :patch,
data: {'user-update' => true},
dataType: 'json',
html: wrapper: :horizontal_form ) do |f|
.panel.panel-default
.panel-body
.col-md-8
= f.input :country, label: 'Country',
= f.button :submit
The controller
def update
@user.update!(user_params)
render json: @user
end
I have tried to add the respond_to
with js
response format, but in that case it tries to convert the @user
to executable javascript. As of the event handler looks like this
$('form[data-user-update]')
.on('ajax:success', function(e, data, status, xhr) {
// The data variable is empty
})
.on('ajax:error', function(e, error, status, xhr) {
$('.simple_form').renderFormErrors('user_data', error.responseJSON);
});
EDIT
Response Header
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
ETag: W/"f53889092c58dc37054386c9504ad1ff"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 712b59ff-8011-4b10-a905-83e559b47452
X-Runtime: 0.101165
Transfer-Encoding: chunked
Request Header
Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,et;q=0.6
Connection:keep-alive
Content-Length:71
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/users/470d573b-b0f1-4822-b036-7d37be6672d6
X-Requested-With:XMLHttpRequest
Response
{
firstName:'John',
lastName: 'Smith',
country: 'USA'
}
Just figured it out while running into the very same problem.
As per http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#dealing-with-ajax-events
I assume you're using rails-ujs instead of older jquery-ujs. In jquery-ujs the code would work and data, status, xhr would be returned; rails-ujs however only returns one attribute - event and additional things are accessed through array on event.details
As per example in the guide
document.body.addEventListener('ajax:success', function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
})
You can access response by calling event.detail[0]
If you've got quite a bit of code relying on this functionality, probably a better bet is to change rails-ujs back to jquery-ujs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With