Reputation: 5552
I have a Rails 5.1 form for creating a user object, which looks like this when rendered:
<form class="upload-form" action="/users" accept-charset="UTF-8" data-remote="true" method="post">
<input name="utf8" type="hidden" value="✓">
...all the fields...
<div class="actions">
<input type="submit" name="commit" value="Submit" data-disable-with="Submit">
</div>
</form>
It submits fine, and the controller actions fires. Here it is:
def create
@user = User.new(user_params)
if @user.save
respond_to do |format|
format.js
end
end
end
But the create.js.erb which is returned does not execute in the browser:
$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
console.log(data);
var field = $('#upload-form').find('input[name=fileinput]');
var file = field[0].files[0];
console.log(file);
});
I am confused as to why this js does not get executed (I can see it returned in the response).
Upvotes: 0
Views: 441
Reputation: 3193
For anyone else tripping across this issue, but the above doesn't help:
I am using CoffeeScript and ran into this same issue. I had a file called index.coffee which would render a partial template into a function to replace a div on the client side. Worked GREAT when I was calling a route the normal way, but would not work when I was rendering it via a "button_to".
Rails was rendering the JS properly, sending it down to the browser, and I could test the JS and it worked fine. But it would not be invoked on the button_to click.
All I did was rename the file to "index.js.coffee" and it started working. Yay, Rails weirdness!
Upvotes: 1
Reputation: 33542
You have defined upload-form
as a class
, but you are calling it as a ID
in the JS
Change
$('#upload-form').on('ajax:success', function(event, data, status, xhr) {
console.log(data);
var field = $('#upload-form').find('input[name=fileinput]');
var file = field[0].files[0];
console.log(file);
});
to this
$('.upload-form').on('ajax:success', function(event, data, status, xhr) {
console.log(data);
var field = $('.upload-form').find('input[name=fileinput]');
var file = field[0].files[0];
console.log(file);
});
Upvotes: 1