lalalalala pqpqpqpqpq wrote in post #1069545:
Hi, I want to link the selections from a drop down menu in my view to a
controller action. Here’s the code for my view:
[code]
<%= link_to "option A", :controller => "scriptrunner", :action
=> "runoptionA" %>
<%= link_to "option B", :controller => "scriptrunner", :action
=> "runoptionB" %>
<%= link_to "option C", :controller => "scriptrunner", :action
=> "runoptionC" %>
[/code]
Are you saying you literally have written the HTML for the select
control in your view template? If so then you should know that Rails
provides some nice helpers for that.
Right now when I select an option from the drop down menu, nothing is
called in my controller.
Of course the controller doesn’t get called. HTML doesn’t work that way.
A request is sent to the server, the server responds with HTML (or other
response types). At this point the server waits for other requests.
The client will generate another request on certain actions. 1. A
hyperlink is clicked or 2. A form is submitted. I think those are the
only two actions that will trigger a new request, without the aid of
something outside of the HTML. That might be JavaScript, Flash or other
browser plugins.
Changing the selection in a popup box, clicking a checkbox, etc. will
not send a request to the server. These actions only modify the form
data that gets POSTed back to the server when a form gets submitted.
Is there a way to add a “GO” button, so after I
select something from the menu, I can click the GO button and it will
call the corresponding action in my controller?
Sure. That is called a form submission. That’s what the is.
However, in most cases a better way would be to use JavaScript/JQuery to
bind a JavaScript function to the “change” event of the select tag. Then
post the data you need back to the server asynchronously using
XMLHttpRequest (A.K.A AJAX).
But, only use AJAX is it’s really necessary. In many cases you can pass
everything you need in the initial request and then use JavaScript
(without AJAX) to control your user interface.
One common use that typically leads to questions like yours, is when one
wants to control one popup’s selection based on a another popup.
Sometimes it’s possible to send all the information the client needs to
accomplish that in the initial request. Thus saving additional round
trips to the server. Other times that’s not possible, or not convenient,
and it’s necessary to call back to the server.
The one thing I would highly recommend is to avoid triggering a page
refresh based on changes to popups or checkboxes. Use JavaScript (and
AJAX if necessary) to do partial updates to your page. Your users will
thank you for that. It’s highly annoying to have your browser window
scrolled to exactly where you want it then changing a popup causes a
page refresh and throws you back to top of the page. This would happen
if you were do use a normal form submit (“Go”) button as you mentioned.