Galil
Galil

Reputation: 869

Run ruby function from HTML form

I have created an HTML form and when I click a button I want to call a ruby function. The HTML form has a text field and and dropdown menu and their values should be given as input parameters to the ruby function.

The ruby function is the following:

  def price(amount, item)
    # code here
  end

I tried to do something like this, but it is obviously wrong:

  fileHtml.puts " <script>
                  function calculatePrice(){
                    document.getElementById('price').value = <% object = MyClass.new %>
                                                                 <%= object.amount(document.getElementById('amount').value, document.form.menu.options[document.form.menu.selectedIndex].value) %>
                                           }

                  </script>"

How could I pass the value of the text field to the "amount" and the value of the dropdown menu to the "item" parameter of the ruby function?

Upvotes: 1

Views: 395

Answers (2)

Felix
Felix

Reputation: 4716

There is too many solutions, but one i reccomend you to look into is sinatra (http://www.sinatrarb.com/), which is a web-microframework.

Then you will use it to:

  • serve the HTML to a webbrowser when the webbrowser visits the sinatra application ("server")
  • On button click (form submission), the webbrowser will talk back to the sinatra ('look, Galil entered 5 in the amount field') app which can do whatever it wants to with that data.

Good luck.

Upvotes: 2

Jerome Anthony
Jerome Anthony

Reputation: 8021

Ruby is a server side language. HTML is client side. In this context Javascript is also client side. You cannot call a server side function from your client code. Think of the browser. It doesn't understand Ruby. So it cannot execute Ruby functions.

You have to expose your ruby function as a web service or a rpc function and call it from your client via ajax.

Upvotes: 0

Related Questions