0

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

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you nick. This is what I was looking for. Now I can see the value in the session. Since I am new to rails, please dont mind if this is a silly question.. I think "GET" requires a template/view for the action.. so I just changed the ajax request to "post", and changed the routes.rb file. Now again the session is not getting updated. Do you see any catch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.