Reputation: 147
I'm having a bit of trouble working with AJAX and Ruby on Rails with JQuery. I'm trying to use the AJAX method in JQuery, do a GET request with it, and transfer the response into Ruby so I can use it in my controllers and views. Here's the script that I want to run at the bottom of my view:
function onClick() {
$.ajax({
url: "/posts.json",
type: "GET",
success: function(response) {
return response;
}
});
};
onClick();
Is there a way I can transfer this response into ruby, so I can use it in my controllers like this? I want 'response' to be what is returned from the AJAX request:
def index
@response = response
end
Thanks in advance!
Upvotes: 0
Views: 745
Reputation: 7522
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:
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!
Upvotes: 1