I'm trying to submit my form to controller using ajax and display ajax response in my view. The form submits using ajax but I'm unable to get to 'ajax:success' or 'ajax:error' methods in my javascript. Below is a code snippet for it:
form.html.erb
<%= form_for @item, :html => { :class => 'form-horizontal' },:id => 'item_form', :remote => true do |f| %>
<div class="control-group">
<div class="controls">
<%= f.text_field :item_title%>
</div>
</div>
<div class="form-actions">
<%= f.submit nil%>
</div>
<% end %>
<%= javascript_tag do%>
jQuery(function($) {
alert ("load")
$('#item_form')
.bind('ajax:success', function(xhr, data, status) {alert ("success")})
.bind('ajax:complete', function(xhr, status) {alert ("complete")})
.bind('ajax:error', function(xhr, data, status) {alert ("error")})
});
<%end%>
controller
def update
@item = Item.find(params[:id])
respond_to do |format|
if @item.update_attributes(params[:item])
format.html {
if request.xhr?
puts "its an ajax req"
render :json => {
:location => url_for(:controller => 'items', :action => 'edit'),
}
end
}
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
It looks like the id you are supplying is not in the correct subhash within the options. The id would have to be inside the html options like so:
<%= form_for @item, :html => { :class => 'form-horizontal', :id => 'item_form' }, :remote => true do |f| %>
Without the html id on the form, your events are not being bound.
Documentation reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for