Ajax|rails
Vi. Use of Form_remote_tag
This form_remote_tag () Help function is similar to Link_to_remote (), except that it also sends the contents of an HTML form. This means that the action processor can use the data entered by the user to form a response. This example shows a Web page-it has a list and an AJAX-enabled form that enables users to add some options to the list.
My view template (index.rhtml) looks like this:
Ajax List Demo <%= Javascript_include_tag "Prototype"%>
Add to list using Ajax <%= Form_remote_tag (: Update => "My_list", : URL => {: Action =>: Add_item}, :p osition => "top")%> NEW Item Text: <%= Text_field_tag:newitem%> <%= Submit_tag "ADD Item with Ajax"%> <%= End_form_tag%>
- Original Item ... please add more!
|
Notice the two parts that are bold above that define the beginning and end of the form. Because the form starts with Form_remote_tag () instead of Form_tag (), the application submits the form using XMLHttpRequest. The parameters in Form_remote_tag () appear to be:
• The update parameter is used to specify the ID of the DOM element and the content to update the action execution result-in this case, my_list.
The URL parameter is used to specify server-side actions-in this case, invoke an action called Add_item.
• The position parameter represents the returned HTML fragment inserted at the top of the my_list element-in this case, a <UL> label
Figure 4. Before adding any items |
My controller class looks like the following:
Class Listdemocontroller Applicationcontroller def index End def Add_item Render_text "" + Params[:newitem] + "" End End |
The Add_item action processor builds an HTML list item fragment that contains any text entered into the NewItem field of the form.
Figure 5. After adding a few new list items |