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
We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.
Use rails-ujs (no jQuery) Making an AJAX POST call with rails-ujs looks identical to making it with jQuery: Rails. ajax({ type: "POST", url: "/things", data: mydata, success: function(repsonse){...}, error: function(repsonse){...} })
Answer: Use the jQuery submit() Method You can use the submit() method to submit an HTML form (i.e. <form> ) using jQuery. The jQuery code in the following example will submit the form on click of the button (i.e. the <button> element) which has the type attribute set to button (i.e. type="button" ).
You want to:
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With