Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • JQuery Ajax Post in Rails with example

    • 0
    • 2
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 2.27k
    Comment on it


    JQuery Ajax Post in Rails

    As we all know, ajax is used for saving some objects to server or requesting to server and in response, page should not be refreshed. Rails provides helper remote: true, that can be added in ruby form helpers. After adding this, the form becomes ajax form and on submission, the page will not be refreshed. Addition of remote in different helpers and their respective HTML's output are given below:

    <%= form_for(@blog, remote: true) do |f| %>
    <% end %>
    # = >
    <form accept-charset="UTF-8" action="/blogs" class="new_blog" data-remote="true" id="new_blog" method="post">
    </form>
    
    #### Similarly for other helpers It can be used as #####
    
    <%= form_tag('/blogs', remote: true) do %>
    <% end %>
    
    <%= link_to "Blog title", @blog, remote: true %>
    
    <%= link_to "Delete blog", @blog, remote: true, method: :delete %>
    
    <%= button_to "Blog title", @blog, remote: true %>
    


    Thus we can see that, by setting remote:true, the html attribute 'date-remote=true' gets enabled. Now lets take an example of a simple ajax form, where we want to save the comment of a user on a blog to server and want to append it below the existing comments without refreshing the page. Suppose our html page for comments is comments.html.erb and @comments instance variable that contains all the existing comments object with user_name and message.

    #comment.html.erb
    <div id="comments" >
        <% if @comments.present? 
            @comments.each do |comment| %>
                <div style="float:left">
                    <%= comment.user_name %>
                </div>
                <div>
                    <%= comment.message %>
                </div>
            <% end %>
        <% end %>
    </div>
    <div id="add-comment">
        <%= form_tag(add_comment_url, method: :post, remote: true, :id => "add_comment_form") do %>
        <div>
            <%= text_area_tag 'message', "",:maxlength => "130",:id => "user_comment", :placeholder => "" %>
            <%= hidden_field_tag 'blog_id', blog.id %>           
            <div id="comment-errors">   
            </div>
            <input type="submit" value="Post">
        </div>
        <% end %>
    </div>
    
    #javascript code for ajax
    <script type="text/javascript">
    $(document).ready(function(){
        $("#add_comment_form").on("ajax:success",function(e, data, status, xhr){
            try{
                var respone = JSON.parse(xhr.responseText);
                $("#comments").append(respone.html);       
            } catch(e) {
                console.log(e);
            }
        });     
    });
    </script>
    
    
    #Controller that handles the request
    def add_comment
        @blog = Blog.where(id: params[:blog_id]).first
        comment = @blog.comments.create(message: params[:message], user_name: current_user.name, blog_id: params[:blog_id]) 
        html = render_to_string :partial => '/blog/comment_info', :locals => {:comment => comment}
        respond_to do |format|
          format.json { render :json => {:success => true, :html => html} }
        end
    end
    
    #partial comment_info has been written as:
    <div style="float:left">
        <%= user.user_name %>
    </div>
    <div>
        <%= comment.message %>
    </div>
    

    Here we are submitting the comment through post to our server and add_comment method adds the comment to the related blog and returns json response. After that we convert it to html, which gets appended at the end of the existing comments.

    Hope you liked this blog. For more Blogs on Rails, Click here.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: