0

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

1
  • I also notice that my form submits twice when I do an ajax submit. I saw few posts which asked to delete public/assets, clear cache and then try again. I tried this as well but it didn't help. Commented Aug 20, 2012 at 5:21

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@user193545: I mimic'd your exact code in a new app with an item scaffold. After fixing the id, I successfully received both the success and complete events. I'm using ruby 1.9.3 and rails 3.2.8. Here are the steps I followed: 1) rails new stackoverflow-test 2) rails g scaffold item item_title:string 3) rake db:migrate 4) rm public/index.html 5) <<copied your code into _form.html.erb & items_controller.rb>> Let me know if there is anything else I can do to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.