ajax request with form_remote_tag doesn't work
So I'm using a form_remote_tag to attempt an ajax form submission, like so:
<%开发者_如何学JAVA form_remote_tag :update=> 'test', :url=> {:action=>'test_action'} do -%>
It renders with no apparent problem:
<form action="/pages/test_action" method="post" onsubmit="new Ajax.Updater('test', '/pages/test_action', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
The test_action action:
def test_action
if request.xhr?
render :text => 'some text'
else
puts 'nope'
end
end
When I submit the form(via the submit button, nothing weird like the jquery submit() event), no ajax request is made. The xhr check returns false. Help please??
In controller you should respond to specified format, js in your case. For example:
def create
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
flash[:notice] = 'Item was successfully created.'
format.js
format.html { redirect_to(@item) }
format.xml { render :xml => @item, :status => :created, :location => @item }
else
format.html { render :action => "new" }
format.xml { render :xml => @item.errors, :status => :unprocessable_entity }
end
end
end
The best practice for now is to use unobtrusive javascript (UJS). There is no form_remote_tag
in rails 3. UJS can be used with rails 2.3 as well.
精彩评论