views:

91

answers:

1

I have started using jQuery and rails. I have made a simple form that submits to the database and updates the page without reloading with ajax.

In my jQuery functions I used $"#new_comment" for the id name (in my application.js and create.js.erb files) but on my places/show view file, I named the div "add_comment" and it works..

I renamed it new_comment and it breaks! Can someone explain it please? I get an error: "no action responded to 1"

My function in my controller is "create".

#views/places/show.html.erb
<div id="new_comment" style="display:none">
 #form goes here
</div>

#application.js
jQuery.fn.submitWithAjax = function(){
    $("#new_comment").submit(function() {
    $.post($(this).attr("action"), $(this).serialize(), null, "script");
    return false;
    })
};


$(document).ready(function() {
    $("new_comment").submitWithAjax();
})

#create.js.erb
$("#new_comment").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');

$("#comments_count").html("<%= pluralize(@comment.place.comments.count, 'suggestion') %>");

$("#comments").append("<%= escape_javascript(render(:partial => @comment)) %>");

$("#new_comment")[0].reset();

#comments_controller.rb
    def create
      @place = Place.find(params[:place_id])
      @comment = @place.comments.create!(params[:comment])

    flash[:notice] = "Thanks for your suggestion. Remember to share with friends!"
    respond_to do |format|
      format.html {redirect_to place_comments_path(@place)}
      format.js
      end
end
A: 

In addition to attaching the submit event to the wrong element, you are restricting your jquery plugin to just #new_comment. You should abstract it some and use the element that you're passing in when you call submitWithAjax. You can add an id to the form or change the selector in your document.ready function to target the child form.

#application.js
jQuery.fn.submitWithAjax = function(myForm){
    $(myForm).submit(function() {
    $.post($(this).attr("action"), $(this).serialize(), null, "script");
    return false;
    })
};


$(document).ready(function() {
    $("#new_comment_form").submitWithAjax();
})

You'll also need to correct the reset call in your create.js. The other javascript appears to do what you expect.

atxryan
That doesn't work but if I use this.submit(function) and use no parameter it works. Thanks.
GreenRails