Reputation: 32823
In my ruby on rails code I want to send back json response to client. Since I am new to ruby on rails I do not know how can I do this. I want to send error = 1 and success = 0
as json data if data does not save to database and if it successfully saves that it should send success = 1 and error = 0
Please see my code below
here is my controller
class ContactsController < ApplicationController
respond_to :json, :html
def contacts
error = 0
success = 1
@contacts = Contact.new(params[:contact])
if @contacts.save
respond_to do |format|
format.json { render :json => @result.to_json }
end
else
render "new"
end
end
end
here is my javascript code
$('.signupbutton').click(function(e) {
e.preventDefault();
var data = $('#updatesBig').serialize();
var url = 'contacts';
console.log(data);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
Upvotes: 0
Views: 2641
Reputation: 9622
You have to adjust your routes to accept json data
match 'yoururl' => "contacts#contacts", :format => :json
Then it will work
Upvotes: 0
Reputation: 712
There are tons of other elegant ways, but this is right:
class ContactsController < ApplicationController
def contacts
@contacts = Contact.new(params[:contact])
if @contacts.save
render :json => { :error => 0, :success => 1 }
else
render :json => { :error => 1, :success => 0 }
end
end
end
Add also a route to routes.rb. If you need to use html response you have to include respond_to do |format|.
Upvotes: 4