I've been googling all day and still couldn't find any answers.So basically in my javascript function, I want to send a GET request to my rails controller and the rails controller will send back a JSON object. Any idea how do I do this? thnx
2 Answers
Using jQuery I would do something like this:
In the selector and event you want, for instance on clicking some element:
$(function() { $('#foo').click( function(){ var params = '{"field1": "value1", "field2: "value2"}'; $.get('/controller/bar', params, function(data){ alert(data); }); }); });
Then in your Rails controller:
def bar /// hack hack hack render :json => {"response" => "OK"} end
The in your routes.rb:
match 'controller/bar' => 'controller#bar'
Finally, change "controller" according to your code. Firebug is your friend!
2 Comments
hlim
Im sorry im still a newby, so after rails sent the JSON object, how can I access that data in my javascript?
anders
@mamonluk you can access the data through the data variable, for instance data.response would be "OK" - you can try it with alert(data.response); - or if you want to show it in the HTML itself in a "response" ID you can do something like $('#response').html(data.response);
you can use jQuery ajax to make get or post request from javascript.
jQuery.ajax({
url: "url to controller method", // it should be mapped in routes.rb in rails
type: "GET",
data: {field1 :value1, field2:value2}, // if you want to send some data.
dataType: "json"
success: function(data){
// data will be the response object(json)
}
});
response from rails will something similar to the below, you can modify as per your requirement.
respond_to do |format|
format.js { render :json => @json_data }
end
1 Comment
hlim
How would rails sent the JSON object back to the javascript then? thnx