jQuery post to Rails
You can setup your post to structure the data in any way as long as it is interpreted correctly on the rails end, but best practice is to have an object of 'model-name' with all the values.
Javascript
$.ajax({
url: "/sub_comments",
type: "POST",
data: {subcomment: {
field: val,
field2: val, etc... }},
success: function(resp){ }
});
Rails
def create
@sub_comment = SubComment.new params['subcomment']
if @sub_comment.save
render :json => { } # send back any data if necessary
else
render :json => { }, :status => 500
end
end
Bob
Updated on June 21, 2022Comments
-
Bob almost 2 years
My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2
I have a form that shows multiple photos and comments for a user and I wish to implement inline commenting.
<div id="newsfeed"> <div> <div class="photo_title">Summer 2011</div> <div class="newsfeed_photo"> <a href="..." /></a> </div> <textarea class="comment_box">Write a comment...</textarea> </div> <div> <div class="comment_title">Seeing a movie</div> <textarea class="comment_box">Write a comment...</textarea> </div>
I want to submit an AJAX post upon the user hitting the enter key in the textarea field. Here's the javascript (incomplete) that I have so far
$('#newsfeed').delegate('.comment_box', 'keydown', function (event){ event.preventDefault(); $.post('/sub_comments', ...); });
I'm using the
delegate
method because<div id='newsfeed'>
contents could be replaced with another AJAX call. What I need is the syntax for jQuerypost
method assuming I need to pass some form params like sayphoto_id
, etc. Assume that I have a way to access the values for the params, what's the syntax for thepost
call to creating params the way Rails expect themHere's the standard Rails bits
sub_comments_controller.rb def new @sub_comment = SubComment.new respond_to do |format| format.html # new.html.erb format.js end end
Also I don't want to use the usual
<%= form_for(@sub_comment, :remote => true) do |f| %>
for each and every inline comment I could add. I have also taken a look at Ryan Bates's railscast but the code looks outdated. -
Mario Zigliotto over 12 yearswould you mind explaining why you chose to not use a
respond_to
block please? thank you! -
DonPaulie over 9 years@MarioZigliotto He did it only because it is shorter to write. The consequences are that he cannot render html in this action, only json.
-
developer01 about 2 years@DonPaulie is it not possible to render JSON in an html.erb view? I know this answer is really old. I'm using Rails 6.
-
DonPaulie about 2 years@developer01 I am not sure if I understand your question. If you want multiple formats, definitely use
respond_to
with block. If you want to build the json in some kind of view file (and not in controller), you can simply name the filecreate.json.erb
and write the contents. But then I would recommend you jbuilder gem or some serializer pattern.