I have looked around and I am either not understanding something, or
just can’t find a way to get a javascript variable posted to into
rails. I have a javascript that runds and takes input from a user, and
I need to get these javascript values into the rails app on the
server. Since this is within a script the ruby link_to_remote and
alike functions won’t work since I need to be within the javascript
script, so I need an example of a javascript/prototype ajax function
or just a submit or post and how I can read variables passed between
on the server side.
That code snippet with send an http request to the specified url (which
will be routed to a controller)…
so
var content = ‘something’;
var url = ‘/posts/create?
message=’+encodeURIComponent(content);
new Ajax.Request(url,
{ asynchronous:true, evalScripts:true, method:‘get’,
onComplete: function(t) { // do something
}
});
Let’s say that following goes to posts/create and it has the variable
attached to it so the full url is:
/posts/create?message=something
This will end an ajax request to the “create” action of the “posts”
controller (assuming the routes) and the “message” param appended at the
end will be accessible in the action via params[:message]
You will probably save yourself some effort here if you create a js
function that you include in the page (e.g., application.js or another
js file you include) and let that function accept the url or an
options hash through which you pass the url. That way you can rely on
Rails’ helpers to build the url for you, decoupling your js from the
Routing system currently used.
As for the Ajax.Request, the posted methods will work but they are a
bit messy. Prototype’s method actually has a ‘parameters’ option that
handles the variables in a cleaner fashion. For example:
You will probably save yourself some effort here if you create a js
function that you include in the page (e.g., application.js or another
js file you include) and let that function accept the url or an
options hash through which you pass the url. That way you can rely on
Rails’ helpers to build the url for you, decoupling your js from the
Routing system currently used.
Also don’t forget about the :with option
(eg link_to_remote ‘Click me’, :url => {…}, :with => ‘put some
javascript here’)
Fred
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.