Data from Javascript to Rails?
February 23, 2007 6:49 PM   Subscribe

How can I pass data created via javascript to my Rails application?

I am working on a Rails application that relies on user input for some data that needs to store in the database. The data is created by the user clicking inside a div at various points, and the data that I need to store is the mouse coordinates where the user clicks.

So, the view loads and the user clicks various places. Of course, capturing the mouse position is easily accomplished. Where I am stuck is in how to pass the array of data that I created wtih Javascript to my Rails controller for processing.

Any help is greatly appreciated.
posted by jxpx777 to Computers & Internet (4 answers total) 1 user marked this as a favorite
 
JSON is great for this sort of thing. Pass it in via AJAX or as a GET or POST parameter with a form submission.
posted by IshmaelGraves at 7:01 PM on February 23, 2007


If you want to submit the whole page, throw the data into a hidden form element, and make the submit just send in the form. Then it's like any other. If you need to do it asyncronously, just use ajax. Just use the normal ajax commands in rails (remote_function looks about right) to call the controller w/ the args.
posted by cschneid at 8:48 PM on February 23, 2007


Seconding what cshneid said. You use the javascript to fill in the "value" attribute of hidden form fields (using normal DOM functions), then submit the form at the appropriate time. Same as any other form processing.
posted by beerbajay at 10:12 PM on February 23, 2007


Ref JSON, you may need to use POST to pass it as there's a limit on the size of a URL, and a JSON object could become quite large. As cschneld suggested, stick it in a hidden form element and POST it into Rails.

I'd suggest using the ScriptAculous libraries to do this:

<input type="hidden" id="json" name="json" value="">

<script>

// Whatever your data object is here
var my_data = { test: ["one","two"] };

// Assuming JSON is a class that can encode or decode
// json data.
$( "json" ).value = JSON.encode( my_data );

</script>
posted by gaby at 5:17 AM on February 24, 2007


« Older Is the famous "Bus Stop" episode "A Lion Walks...   |   Biodiesel warranty Newer »
This thread is closed to new comments.