I am using Rails 3, Jquery-UJS and Jquery. I have a working setup of Jquery with Rails3 .I am trying to send a variable from Javascript to Rails controller by clicking a link.
My current approach is using js as follows to make an ajax call and pass msg string.
$("#select_link").click(function()
{$.ajax({
type: 'POST',
url: 'http://your_url/jmsg',
data: {msg: "hello world"},
;}
});
});
Should I include this code in my application.js file?
In my .html.erb file I have
<%= link_to "Send variable", jmsg_path, :remote => true %>
In my controller I have
def jmsg
@message= params[:msg]
respond_to do |format|
format.js
end
end
Till now, I've not been able to get the javascript variable in my @message instance variable
EDIT:
I made changes as suggested. However, the variable @message is not set when I do
@message=params[:msg]
When I check XHR using Fiebug, I see 302 Moved Temporarily for the POST action (the POST parameter msg is set correctly though). Response is - $("#show_message").html("")
My .js view is:
$("#show_message").html("<%= @message %>")
EDIT2 : When I check Firebug, it shows that there are two actions now: 1. POST /jmsg - with response @message = "hello world" 2. GET /jmsg - with response @message= " "