19

In my Rails 5 application a form's default submit button is disabled on submit to prevent an accidental double submit. Whenever the page is redirected after the submit or re-rendered with validation errors, the button is enabled again.

In my situation I have the controller send a zip file that I build in memory in the controller action using the following:

send_data zip.read, filename: "some_file.zip"

However, after serving the file the form is not re-enabled. I have to ctrl-F5 the page to reset the form and be able to make a different selection.

What is the rails way to do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ChrisDekker
  • 1,584
  • 18
  • 39
  • It sounds like maybe you're using ajax, or UJS, to send this form? – steel Dec 01 '16 at 04:16
  • The form is a normal `form_tag` not associated with a model. Normally a form submit renders a new page (or redirects) as a response. Here a file is served through send_data as a response but no page is reloaded, causing the `submit_tag` to stay disabled. – ChrisDekker Dec 05 '16 at 23:54
  • @ChrisDekker ever found a solution for this? I have the same issue. – Daniel Oct 17 '18 at 12:32

3 Answers3

5

I ran into a similar problem and resolved by using button_tag instead of submit_tag. This doesn't re-enable the form, but stops it from being disabled.

Colin
  • 2,814
  • 5
  • 27
  • 37
  • Could you show an example? What behavior did you get from that? To me, the problem seems like catching the event on the client side when the response is given with the file. I don't really see how using a `button_tag` could help with that. – ChrisDekker Dec 22 '16 at 15:11
  • 1
    It's because `button_tag` isn't triggering the disable at all, which may be acceptable for your use case. It won't prevent double-clicks at all. I ran into the problem a little differently - my form is `target="_blank"`, but since it doesn't cause any backend changes, it's not an issue if mine is double clicked. – Colin Dec 23 '16 at 06:15
1

Take a look at this approach for detecting download events with a combination of client and server: Detect when browser receives file download

Community
  • 1
  • 1
Colin
  • 2,814
  • 5
  • 27
  • 37
1

You can keep submit_tag being enabled by add append data: { disable_with: false }.

Or enable it after form submitted a few seconds?

 $("#my_form_id").submit(function(){
    setTimeout(() =>{
      
      // Enable submit button or enable all
      // $.rails.enableFormElements($($.rails.formSubmitSelector))
      $.rails.enableFormElement($("#my_form_id [type='submit']"))

    }, 3000)
  })
Fangxing
  • 5,716
  • 2
  • 49
  • 53