Praveen R
Praveen R

Reputation: 200

How to display validation error in rails using AJAX

enter image description hereI need to display the validation error of my post model. I have used AJAX call to create a post into the index page of the post. So that when the NewPost button is clicked it will display the new post form partial into the index page. While creating the post in index page if there is any validation errors found, the errors are displayed and it renders the new post form partial in js format again so that the new post form appears twice along with the validation error.

Posts controller:

def create
  @post = @topic.posts.build(post_params)
  @post.user = current_user
  respond_to do |format|
    if @post.save
      # Success
    else
      format.js { render 'posts/new' }
    end
  end
end

Create.js.erb file:

alert("Post created Successfully");
$('.new_post').hide();
$('.new_one').show();
$('.post_div').prepend('<%= j render @post %>');
Index.html.erb file:

<div class="container" >
  <% if params[:topic_id].present? %>
      <h2 align="center"><span class="em-text"><%= @topic.topicname %> Posts</span></h2><hr>
      <%= link_to "New Post", new_topic_post_path, :class => 'btn btn-primary new_one' ,remote: true%> <br><br><br>
   <% else %>      
      <h2 align="center"><span class="em-text">All Posts</span></h2><hr>
    <% end %>
<div class="post_div">
 <%= render @posts %>
</div>
    <%= will_paginate @posts, renderer: BootstrapPagination::Rails %>
</div>
Post partial for new post form:
<%= form_for [@topic, @post],remote: true,html: {multipart: true}, url: topic_posts_path do |f| %>

  <% if @post.errors.any? %>
    <% @post.errors.full_messages.each do |msg| %>
      <div class="alert alert-danger"><%= msg %></div>
    <% end %>
  <% end %>
  <div class="form-group">
    <%= f.label "Title" %><br/>
    <%= f.text_field(:title,{:class => 'form-control', :placeholder => 'Enter the Title'}) %>
  </div>

  <div class="form-group">
    <%= f.label "Body" %><br/>
    <%= f.text_area(:body, {:class => 'form-control', :placeholder => 'Enter the Post Body'}) %>
  </div>

  <div class="form-group">
    <%= f.submit({:class => 'btn btn-primary'})%>
  </div>
<% end %>
new.js.erb file:

 $('.new_one').hide().after("<%= j render 'form' %>")

Upvotes: 0

Views: 978

Answers (1)

NAREN PUSHPARAJU
NAREN PUSHPARAJU

Reputation: 165

Use can like this

<% if @post.errors.any? %>
alert("ERROR(S):\n<%= j @post.errors.full_messages.join("\n") %>")

Check the post whether it has any errors if error exists alert the error else do something

Upvotes: 2

Related Questions