jQuery post to Rails
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 jQuery post
method assuming I need to pass some form params like say photo_id
, etc. Assume that I have a way to access the values for the params, what's the syntax for the post
call to creating params the way Rails expect them
Here's t开发者_高级运维he 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.
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
精彩评论