I am a beginner in rails and jQuery. I have two separate forms in one page and I want to submit them separately in ajax way (with jQuery). This is how far I got. Can anybody add or fix this code to make it work. I am using Rails 3.1 and jQuery 1.6. Thank you in advance.
application.js
$(".savebutton").click(function() {
$('form').submit(function() {
$(this).serialize();
});
});
first form:
<%=form_for :users do |f| %>
<fieldset>
<legend>Basic details</legend>
<%= f.label :school %>
<%= f.text_field :school,:size=>"45",:class=>"round",:id=>"school" %><br/>
</fieldset>
<p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>
second form:
<%=form_for :courses do |c| %>
<fieldset>
<legend>Your current classes</legend>
<label>class:</label><%= c.text_field :subject,:size=>"45",:class=>"round" %><br/>
</fieldset>
<p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>
SchoolController
class SchoolController < ApplicationController
respond_to :json
def create
@school = current_user.posts.build(params[:school].merge(:user => current_user))
if @school.save
respond_with @school
else
respond_with @school.errors, :status => :unprocessable_entity
end
end
end
CourseController is in the same shape as SchoolController
You want to:
The code below should do that:
it's very important in your request with ajax stop the beahavior default, send remote:true in your form_for
in your ajax
Nothing here worked for me, my issue was the jQuery modal library would break my forms from being submitted via remote data if I brought up a modal window, but I found a fix.
First add the jQuery Form Plugin to your assets javascript directory: http://malsup.github.io/jquery.form.js
Now override the submit method for your form. For example you could do something like this:
To submit form via AJAX you could just pass
:remote => true
to theform_for
helper. By default rails 3.0.x uses prototype js lib, but you can change it to jquery with thejquery-rails
gem (which is the default for rails 3.1).bundle install
it and thenrails g jquery:install
to replace the prototype files with jquery.After that you'll just need to handle the callback. Take a look at this screencast
If you use
:remote => true
on your forms, you can submit them with JavaScript withThe preferred way in Rails 3 to do ajax form submission is to utilize Rails-ujs.
Basically you allow Rails-ujs to do the ajax submit for you (and you won't need to write any js code). Then you just write js code to capture the response event (or other events) and do your thing.
Here are some code:
First, use the remote option in form_for so form will submit via ajax by default:
Then when you want to do some action based on ajax response status (e.g. successful response), write the javscript logic like this:
There are several events which you can hook to.