1

Is it possible to execute a Javascript function included in application.js or the corresponding js.coffee file from a controller, but without rendering or reloading the view? I.e. just a simple

def connect()
  call js: "connect_through_javascript();"
  render :nothing => true
end

but instead of rendering :nothing, is there some way the view could be left untouched? Also would it be possible to send params with it, i.e.

def connect(param1, param2, param3)
  call js: "connect_through_javascript(#{param1}, #{param2}, #{param3});"
  render :nothing => true
end

The Javascript function called will in turn go to another controller action for it's callback.

I'm about to try with the Paloma gem, but I just wanted to know if any of this is possible without adding dependencies.

1 Answer 1

2

What you want is AJAX. JavaScript will then have to do something intelligent with the HTTP response body in the success callback if using a JavaScript library, like jQuery, or if the readyState is 4 and the status is 200 if using native JavaScript.

You're stuck with the HTTP request-response lifecycle.

EDIT: Here is a simple example:

The HTML

<ol id="comments"></ol>

<script type="text/javascript">
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            document.getElementById("comments").innerHTML = this.responseText;
        }
    };

    xhr.open("GET", "/posts/123/comments_ajax");

    xhr.send(null);
</script>

The Rails Controller

class PostsController < ApplicationController

    def comments_ajax
        @comments = Comment.where(:post_id => params[:id])
    end

end

The contents of app/views/posts/comments_ajax.html.erb:

<%= @comments.each |comment| do %>
    <li><%= comment.text %></li>
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the very clear implementation example. :) The Paloma gem seems to work for my current problem but in some cases I'd prefer your solution.
I haven't used Paloma before. Looks interesting. I gather that it's a Ruby class lib for making Ajax easier on the Rails side, plus a JavaScript class lib to make creating JavaScript classes to interact with Rails RESTful services easier?

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.