Reputation: 2951
I have two questions.First, i have tried to submit a rails form with jquery (ajax method),but i am not sure if it really saved the data,so can anybody double check my code if it is correct?Secondly according to my controller how could i display the data i just saved?I am using Rails 3.1,Sqlite 3.Thank you in advance. Here is my code
FORM
<%=form_for :user 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").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: 250
Reputation: 5104
while I haven't read your code in depth, to answer the question of whether to double check things got saved you can either read the console output or open up the database console
Opening database console:
On commandline type
rails dbconsole
You should be booted into sqlite. From here some useful commands are:
.schema
select * from tablename;
Hope this helps!
Upvotes: 0
Reputation: 9018
You can also use rails console
or rails console --sandbox
for this. Sandbox means you can play with your database in console and it will stay unchanged. Just open the console and type
School.last
after you submitted the form. You should see a hash of values you've just entered in form.
I've found a solution to your problem after looking into server log. You are using GET method instead of POST for your ajax request. Also, you don't have $(document).ready(function() {});
anywhere so your javascript code will never be triggered.
Change your application.js code to this:
$(document).ready(function(){
$(".savebutton").click(function() {
$('form').submit(function() {
var formToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formToSubmit,
dataType: "JSON"
});
return false;
});
});
});
Remember, server log is your friend in debugging ajax, this time it was telling you that you're using a wrong method (GET).
Upvotes: 1