maki
maki

Reputation: 535

rails render view via ajax

I have a new form which I want to render via ajax if it doesn't pass validations

In my controller I have:

def create
  event = CEvent.new(params[:c_event])

  respond_to do |format|
    if event.save
      format.html { redirect_to admin_c_events_path }
    else
      format.js {redirect_to new_admin_c_event_path(:event => event.as_json, :errors => event.errors )}
    end
  end
end

the form has :remote => true param, when I click on submit button, the form is submited via js but nothing renders, when I reload the page info I need renders ok and I reload the page again the empty new form renders.

my console output:

Started GET "/admin/c_events/new?errors=%23%3CActiveModel%3A%3AErrors%3A0x007f74780d1d50%3E&event%5Babout%5D=&event%5Bbackground_content_type%5D=&event%5Bbackground_file_name%5D=&event%5Bbackground_file_size%5D=&event%5Bbackground_updated_at%5D=&event%5Bcontact_person_id%5D=11&event%5Bcreated_at%5D=&event%5Bfinish_at%5D=2014-01-13+11%3A19%3A00+UTC&event%5Bid%5D=&event%5Blocation%5D=&event%5Bname%5D=dewqr&event%5Bpress%5D=&event%5Bpress_contact_person_id%5D=11&event%5Bstart_at%5D=2014-01-13+11%3A19%3A00+UTC&event%5Bupdated_at%5D=&event%5Bvideo%5D=" for 127.0.0.1 at 2014-01-13 13:19:43 +0200
Processing by Admin::CEventsController#new as JS
  Parameters: {"errors"=>"#<ActiveModel::Errors:0x007f74780d1d50>", "event"=>{"about"=>"", "background_content_type"=>"", "background_file_name"=>"", "background_file_size"=>"", "background_updated_at"=>"", "contact_person_id"=>"11", "created_at"=>"", "finish_at"=>"2014-01-13 11:19:00 UTC", "id"=>"", "location"=>"", "name"=>"dewqr", "press"=>"", "press_contact_person_id"=>"11", "start_at"=>"2014-01-13 11:19:00 UTC", "updated_at"=>"", "video"=>""}}
  Person Load (1.2ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%member%')
  Person Load (0.5ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%mentor%')
  Rendered admin/c_events/_select_speakers.html.erb (4.0ms)
  Startup Load (0.4ms)  SELECT "startups".* FROM "startups" 
  Rendered admin/c_events/_select_startups.html.erb (4.6ms)
  Rendered admin/c_events/_schedule_fields.html.erb (13.8ms)
  CACHE (0.0ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%member%')
  Rendered admin/c_events/new.html.erb within layouts/admin (116.0ms)
  Rendered layouts/_header.html.erb (3.3ms)
  Rendered admin/_top_bar.html.erb (4.8ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 10216ms (Views: 180.0ms | ActiveRecord: 2.1ms)

Is where a way to render a view without reload the page?

Upvotes: 0

Views: 483

Answers (2)

HarsHarI
HarsHarI

Reputation: 911

jsut replace by this

format.js {render json: event}

Upvotes: 1

rmagnum2002
rmagnum2002

Reputation: 11421

!NOT a copy/paste ready code, but this always worked for me.

Leave the remote: true to the form to make it as an ajax request and add format.js as a response in controller at create action.

application controller

  ...
  after_filter :add_flash_to_header
  ...

  def add_flash_to_header
    # only run this in case it's an Ajax request.
    return unless request.xhr?

    # add different flashes to header
    response.headers['X-Flash-Error'] = flash[:error] unless flash[:error].blank?
    response.headers['X-Flash-Warning'] = flash[:warning] unless flash[:warning].blank?
    response.headers['X-Flash-Notice'] = flash[:notice] unless flash[:notice].blank?
    response.headers['X-Flash-Message'] = flash[:message] unless flash[:message].blank?

    # make sure flash does not appear on the next page
    flash.discard
  end
  ...

create.js.erb

<% if @cevent.valid? %>
  $("#new_cevent")[0].reset();
  //something more you might need
<% else %>
  $(document).find(".new_cevent").prepend("<%= j(render 'shared/error_messages', object: @cevent) %>");
<% end %>

views/shared/_error_messages.html.erb

<% if object.errors.any? %>
  <div class="alert alert-danger alert-block">
    <h2><%= pluralize(object.errors.count, "error") %> prohibited this schedule from being saved:</h2>
    <button type="button" class="close" data-dismiss="alert">x</button>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

Upvotes: 1

Related Questions