javascriptjqueryruby-on-railsajaxrjs

Ajax and Json with Rails


I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.

But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?


Solution

  • My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so @my_json = some_object.to_json() Then, your instance variable is available in your view

        <script type = 'text/javascript'>
            var theJSON = <%= @my_json %>
        </script>
       

    Now, your data is available in the DOM, parsed nicely into JSON.

    If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.

    Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript