You're mixing up the front-end and the back-end of your application. Your JavaScript code lives in the front-end, which is actually running in your visitors' browsers; whereas your Rails controller lives in the back-end, which is running far, far away on your web server. It's possible to send data back and forth between them, but only as part of the request lifecycle, which I'll summarize as:
- Visitor makes a request to load your webpage.
- Your server & Rails receive the request, and decide how to route it to a controller
- Your controller handles the request, does stuff, and then renders a view into HTML (or JSON, or whatever format you want to send back).
- This HTML (or JSON) is sent back to the visitor as the response. This response contains all of your JavaScript code, as well (actually, your JS code is usually sent in a separate request, made in parallel by the visitor's browser... but it all ends up in your visitor's browser nonetheless).
So, what you're asking for -- to have a JavaScript call send its data to the controller -- is impossible to do in one request. You could have the JavaScript send that data through a new request to the controller, but the visitor wouldn't see that.
Instead, I think you just want to have your controller make this web request, or -- since the request is on your same server anyway -- have your controller simply load all the Posts in your database and send that data to the view. For example:
# app/controllers/things_controller.rb
class ThingsController
def index
@posts_json = Posts.all.to_json
end
end
Then, pass that variable into your JavaScript via a small script in your view (this part is a bit tricky; you need to tell Rails that it's okay to print the JSON string as-is, without sanitizing it):
# app/views/things/index.html.erb
<h1> Posts! </h1>
<script type='text/javascript'>
var posts = <%=raw @posts_json %>;
alert("I've got " + posts.length + " posts loaded.");
</script>
The above is a fairly standard strategy. Hope this explanation has helped!