Topic: Set a rails variable equal to the result of a javascript function?

Can anyone tell me how to call a javascript function in rails (eg in a view page) so that i set a local rails variable equal to the result?  I'm sure this is simple but i'm new to rails and javascript and can't find the answer anywhere.

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Set a rails variable equal to the result of a javascript function?

This not that simple, and depends on what you want to do exactly.

One way would be to set the value of a hidden form field to the Javascript var value, it will be available in the controller in the params hash after the form was submitted.

Re: Set a rails variable equal to the result of a javascript function?

Duplex wrote:

This not that simple, and depends on what you want to do exactly.

One way would be to set the value of a hidden form field to the Javascript var value, it will be available in the controller in the params hash after the form was submitted.

Thanks duplex, but would you mind spelling it out for me a bit more?

I have a javascript function called getUrl() that takes an iframe object and returns its url (and a similar function to get the iframe's current  contents' title): it looks like this

function getUrl(iframeName) {
return top.iframeName.location.href;
}

I want to use this when the user hits a link called 'save this page', which calls an action called "add_current":

<%= link_to 'Save this page', :action => 'add_current' %>

So where does the form go exactly?  And how do i use it?  (sorry for the ignorance)

thanks for the help!

Last edited by Max Williams (2007-07-24 10:56:04)

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Set a rails variable equal to the result of a javascript function?

Instead of a "Save this page" link, use a fo. I also changed the Javascript fucction a bit:

<script>
  function setURLAndSubmit(iframeName) {
    $('url').value = top.iframeName.location.href;
    $('saveform').submit;
}
</script>
<form id="saveform" action="controller/add_current" method="post">
<input type="hidden" id="url">
<input type="submit" value="Save this Page">
    onclick="setURLAndSumbmit('name_of_iframe'); return false;"
>
</form>

That code is just demonstration and might not work for you like that, but i think you get the idea.

Note: the Javascript above requires Prototype Library, so make sure you do

<%= javascript_include_tag :defaults %>

in your layout's head

Last edited by Duplex (2007-07-24 11:23:08)