Submit form in rails 3 in an ajax way (with jQuery)
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.开发者_StackOverflow社区 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:
- Stop the normal behaviour of submit.
- Send it through ajax to the server.
- Get a reply back and change things accordingly.
The code below should do that:
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
If you use :remote => true
on your forms, you can submit them with JavaScript with
$('form#myForm').trigger('submit.rails');
The 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:
form_for :users, remote:true do |f|
Then when you want to do some action based on ajax response status (e.g. successful response), write the javscript logic like this:
$('#your_form').on('ajax:success', function(event, data, status, xhr) {
// Do your thing, data will be the response
});
There are several events which you can hook to.
To submit form via AJAX you could just pass :remote => true
to the form_for
helper. By default rails 3.0.x uses prototype js lib, but you can change it to jquery with the jquery-rails
gem (which is the default for rails 3.1). bundle install
it and then rails 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
it's very important in your request with ajax stop the beahavior default, send remote:true in your form_for
<%= form_for :session, url: sessions_path, remote: true, html: { class: "form-signin" } do |f| %>
<% end %>
in your ajax
$(".form-signin").on("submit", function(e) {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: "POST",
dataType: "json",
success: function(response) {
console.log(response)
},
error: function(xhr, textStatus, errorThrown) {}
});
e.preventDefault(); //THIS IS VERY IMPORTANT
});
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:
= form_for @object, html: {class: "ajax_form_submit"}, authorization_token: true do |f|
= f.text_input
javascript:
$(document).on('ready page:load', function() {
$(".ajax_form_submit").submit(function () {
var form = $(this)
form.ajaxSubmit({
success: function (responseText, statusText, xhr) {
console.log('success: ajax_form_submit')
},
error: function (jqXHR, statusText, errorThrown) {
console.log('error: ajax_form_submit');
console.log(jqXHR, statusText, errorThrown);
}
})
})
})
精彩评论