0

This should be a common answer but I've searched and can't find it. I created a <div class"xyz" style= "display:none" which houses a partial. The form I submit is a get request on the index of my view's controller. I have no problem running javascript on form submission, but I want to perform some javascript after the page reloads so I can unhide my div. Keep in mind this is not a remote ajax form.

index.html.erb: Here is the div that is hidden that I want to unhide after page reloads:

<div class="six wide column" >
  <div id="clients_piece_tab_container" style="display: none;">
    <%= render :partial => 'client_piece_tab'%>
  </div>
</div>

index.html.erb My form submits on the index using a form_tag

<%= form_tag('clients', action: :index, method: :get) do%>
  <%= render :partial => 'update_available'%> # <--Not the div/partial Im trying to unhide.
  <br/>
    <div class="four wide column"> <%=submit_tag "Get Clients", class: "ui primary button"%></div>
<%end%>

What I think I know is that I should be able to trigger index.js.coffee after the get request completes. But I've tried the following with errors about 0 arguments of 1:

clients_controller.rb

respond_to do |format|
  format.js {}
end
ctilley79
  • 2,151
  • 3
  • 31
  • 64

1 Answers1

0

In Rails just respond with a view as normal.

Inside that view put this somewhere:

<script>
    // rails should fill in form_submitted to true or false...
    var form_was_submitted = <% form_submitted %>;
    // idiomatic jquery for running on page load
    $(function () {
        if (form_was_submitted) {
            console.log ('this runs on page load');
        }
    });
</script>

If you want to do without jquery then see this SO answer

Another way to do it might be to use AJAX:

<script>
    $('#clients').on ('submit', function (event) {
        // this runs when the user submits the form

        // prevents the form from actually reloading the page
        event.preventDefault ();

        // ajax requests are async
        $.ajax ({
            url: '/path/to/index',
            method: 'GET',
            data: { something: 'something' }
        }).success (function (server_response) {
            // this function runs after the ajax request completes
            console.log ('server responded with ', server_response);
            // show the div
            $('#clients_piece_tab_container').show ();
        });
    });
</script>
Community
  • 1
  • 1
erapert
  • 1,383
  • 11
  • 15