Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're using a more recent version of Rails, and wanted to do this in an unobtrusive fashion as possible, you'd use the :respond_to options in your controller, like so:</p> <pre><code>class MyController &lt; ApplicationController def first_method respond_to do |format| format.html # this handles normal requests asking for html format.js # this handles requests asking for javascript to be sent instead end end end </code></pre> <p>If you're responding to a click, you'd do something like firing the query like so on the page</p> <pre><code>$("a.element_you_click_to_trigger").click(function(e) { e.preventDefault(); // make sure clicking doesn't trigger unneeded event bubbling $.ajax({url: "/controller/first_method", type: "POST", dataType: "script"}); // send a request and tell the server that you want javascript back } </code></pre> <p>Just like you have an index.html.erb file in your views folder for that controller, you'd have a similar <code>first_method.js.erb</code> file in relevant views folder along side your <code>index.html.erb</code> file:</p> <pre><code>views controller index.html.erb first_method.js.erb </code></pre> <p>This will return javascript that gets executed client side, but it gets build server side, so you can contain rails ERB fragments, so you can do something like this:</p> <pre><code>$('#loading_placeholder_element').html('&lt;%= escape_javascript(render(:partial =&gt; "create")) %&gt;'); // do some other stuff you fancy in the page // then make the next call once the other stuff is over (you may need to add this as a call back on an animation): $.ajax({url: "/controller/second_method", type: "POST", dataType: "script"}); </code></pre> <p>You'd then repeat the same process again for each of the others longer methods that fsmf highlighted.</p> <p>I found this <a href="http://railscasts.com/episodes/136-jquery" rel="nofollow noreferrer">Railscast on jQuery</a> incredibly helpful when I was learning this a couple of months ago, and I'd really recommend it.</p> <p>Hope this helps !</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload