-1

Possible Duplicate:
Ruby on Rails: Sending javascript data to ruby controller

Total noobie with JSON, javascript and RoR

In my RoR application I have some javascript on a webpage. I would like to pass in one of the arrays I have built up to a Ruby function in my controller (is that possible?)

I've read somewhere I need to convert to JSON. Using this command gives me something I can work with (totalChanges is my array)

JSON.stringify(totalChanges)

but how do I pass this to a ruby function? If anything doesn't make sense please straighten me out.

Thanks

EDIT:

I'm using jquery. The comments have pointed out that I can use something like http://api.jquery.com/jQuery.ajax/ to send data over to a controller.

the particular action I want to do is save some data (in a javascript array) to a database and then reload the page to show the new data. jquery.ajax just seems to have so many options I'm a bit lost.

Community
  • 1
  • 1
bdeonovic
  • 4,130
  • 7
  • 40
  • 70
  • Typically you would use AJAX to send the data to a Method on a Controller for your MVC app. – jcolebrand Jun 25 '12 at 21:00
  • is there anyway I can use javascript?? – bdeonovic Jun 25 '12 at 21:03
  • Yes, javascript is part of AJAX. Hit [wikipedia](http://en.wikipedia.org/wiki/Ajax_(programming)) and spend five minutes reading before continuing to ask. Asynchronous Javascript And XML (however we also use JSON because it's "lighter" over the wire, often at about 30-40% less data transmitted in that way) – jcolebrand Jun 25 '12 at 21:04
  • Also, this may help you: http://stackoverflow.com/questions/6451132/how-to-use-the-jquery-ajax-request-and-the-ruby-on-rails-render-method-toghete – jcolebrand Jun 25 '12 at 21:11
  • Why did you create [two questions](http://stackoverflow.com/questions/11198073/ruby-on-rails-sending-javascript-data-to-ruby-controller) on this within an hour? Also, given the information in that question, you already knew everything I just told you :( – fresskoma Jun 25 '12 at 22:53

1 Answers1

1

You can place an AJAX request using jQuery like this:

$.ajax({
    type: "POST",
    url: "/route/to/action",
    data: { mydata: JSON.stringify(totalChanges) },
    success: function(response, textStatus, jqXHR) {
        console.log("Yay it worked.", response);
    }
);

In your action, you can then retrieve the data passed to your action like this:

def action
    mydata = params["mydata"]
    # Save it to the database...
end
fresskoma
  • 25,481
  • 10
  • 85
  • 128
  • thats what I ended up doing. Thanks :) I actually found the code somewhere else but ran into more trouble – bdeonovic Jun 26 '12 at 00:15