0

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).

4
  • probably the name of js file should be create.js.erb Commented Jul 7, 2017 at 13:32
  • it is called create.js.erb. Question updated Commented Jul 7, 2017 at 13:34
  • 1
    You appear to be targeting a form with an ID of upload-form, but your form has a class of upload-form... Commented Jul 7, 2017 at 13:35
  • Omg, well spotted. Doh! Commented Jul 7, 2017 at 13:37

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.