Reputation: 3
I need to pass a variable which is captured from client side via jquery to controller, so that it can be used in the server side. After googling a bit, I found that we can pass it via an Ajax call.
routes.rb
get "mymethod?Id=", :to => "sample#mymethod"
j1.js
$(function(){
var test = 1;
$(.btn).click(function(){
$.ajax({
url: '/mymethod?Id='+ test,
success: function(data) {
}
});
});
});
sample_controller.rb
def mymethod
session[:Id] = params["Id"];
end
When I try to use session[:Id], it is always nil.
Any ideas,
Thanks
Upvotes: 0
Views: 2084
Reputation: 1771
If you want to make a GET request in jquery you'd be better off doing:
$.ajax({
url: '/mymethod',
success: function(data){ // anything },
data: { Id: test }
});
Because it urlencode and format the parameters correctly for you.
In rails, remove the reference to the Id in routes.rb
and just use the params
dictionary in your controller to access the variable Id (info here: http://rails.nuvvo.com/lesson/6371-action-controller-parameters)
Upvotes: 2