user797963
user797963

Reputation: 3027

Rails 4 show ajax loader on remote=true form submission

I'm new to rails and am having trouble figuring out where in the "magic" I can handle an event to show an ajax loader when my ajaxified form is submitted, and hide the loader when my ajax response is returned and displayed to the user.

Here's what I have, where can I add a .js file or function to bind/run on click to show the loader? I know I can remove the loader in the runCMD.js file.

Controller:

def runCMD

    @cmdType = params['commit'].downcase #commit is name of submit button clicked

    //do some stuff, removed for brevity...
    @output = //buncha stuff that happens, but returns output of the commands ran
    @outputVersions = //buncha other stuff, but sets this var

    respond_to do |format|
            format.js   { }
    end

    #render 'testServer'

end

View:

<%= form_tag('/runCMD', :method => 'post', :remote => true) do %>
    <%= select("versions", "version", @outputVersions) %>
    <%= submit_tag "Activate", class: "run-cmd-button" %>
    <%= submit_tag "Stop", class: "run-cmd-button" %>
    <%= submit_tag "Start", class: "run-cmd-button" %>
    <%= hidden_field_tag 'component', @component %>
<% end %>

<br />
<div id="ajax_output" contenteditable="true" style="background-color:black;font-size:10pt;font-family:Courier New;overflow-y:auto;height:1000px;width:1180px;">

</div>

.js file

  $('#ajax_output').html("<%= escape_javascript(render partial: 'cmdOutput', locals: { output: @output } ) %>");

Partial

<% output.each do |line| %>
    <% line.gsub! '[33m', '<font color="yellow">' %>
    <% line.gsub! '[32m', '<font color="green">' %>
    <% line.gsub! '[31m', '<font color="red">' %>
    <% line.sub! '[0m', '<font color="white">' %>
    <% line.sub! '[0m', '</font>' %>
    <% line.gsub! '[0m', '' %>

    <%= raw(line) %>
    <br />
<% end %>

Upvotes: 2

Views: 3237

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 3427

you can add your ajax loader on jquery submit form event.

$( "form" ).submit(function( ) {
  $('#ajax_output').html("loading...")
});

Now on ajax success your ajax_output div html will be replaced with new content.

as per your comment, you can add it in same view where u have the form

<script type="text/javascript">
     $( "form" ).submit(function( ) {
      $('#ajax_output').html("loading...")
    });
</script>

make sure you have jquery.

Upvotes: 5

Related Questions