katie
katie

Reputation: 2951

Ajax function can't save the data from rails form

When i hit savebutton the form is not submitted,what could be wrong with my code?Thank you in advance.I am using Rails 3.1

FORM

 <%=form_for :user ,:remote=>true do |f|%>
 <%= f.label :school %>
 <%= f.text_field :school,:size=>"45",:class=>"round",:id=>"school" %>
 <%= f.submit "save and continue",{:class=>"savebutton" }%>
 <%end%>

JQUERY(application.js)

$(".savebutton").bind('click',function() {  
  $('form').submit(function() { 
    var formToSubmit = $(this).serialize();
    $.ajax({
      url: $(this).attr('action'), 
      data: formToSubmit,
      dataType: "JSON" 
     });
    return false; 
  });
});

CONTROLLER

class SchoolController < ApplicationController
  respond_to :json

  def create
    @school = current_user.schools.build(params[:school].merge(:user => current_user))

    @school = current_user.school.build(params[:school].merge(:user => current_user))

    if @school.save
      respond_with @school
    else
      respond_with @school.errors, :status => :unprocessable_entity
    end
  end
end

Upvotes: 0

Views: 699

Answers (2)

Dylan Markow
Dylan Markow

Reputation: 124429

Well @vinceh's answer is definitely the way you should be doing this, you still can do it the old-fashioned way like you are.

The .submit() method does not submit the form (you may be thinking it does), but instead binds the form's submit event to the method you provide. So right now, when you click the submit button, all it does is set up the callback, but then you return false so the form never actually gets submitted.

You should just be able to get rid of the surrounding $('.savebutton).click(...) handler and put the $('form').submit(...) handler directly in your javascript, so that when the page loads, the callback is registered immediately. You don't need to worry about handling the .savebutton click specifically.

Also, your Ajax request probably needs a type: 'POST' or type: 'PUT', since $.ajax defaults to GET requests.

Upvotes: 1

vinceh
vinceh

Reputation: 3510

If you want to use ajax, you need to add :remote => true in your form_for and with Rails you don't need to explicitly call $.ajax if your form has :remote => true. Read this for a good tutorial on how to use AJAX in your Rails applications.

Upvotes: 1

Related Questions