lazyprop lazyprop - 5 months ago 7
Ajax Question

Rendering a partial after a successful form create with ajax

My controller code:

class HitChallengesController < ApplicationController

def create
game = Game.find(params[:id])
suite_id = Suite.find_by(suite_number: params[:hit_challenge][:suite_id], game_id: game.id).id
@hit_challenge = HitChallenge.new(game_id: game.id, suite_id: suite_id, title: params[:hit_challenge][:title])
if @hit_challenge.save && request.xhr?
respond_to do |format|
format.json { render json: @hit_challenge}
end
else
redirect_to games_show_path(game)
end
end
end


View partial:

<%if @game.has_hit_challenge %>
<h4>Hit Challenges: </h4>

<%if @hit_challenges.count > 1%>
<% @hit_challenges.each do |h|%>
<li>
<%= "Suite #{h.suite.suite_number}, #{h.title}:" %>
<%= link_to "Status", hit_status_path(h) %>
<%= link_to "Play", play_hit_challenge_path(h) %>
<%= form_for h, url: delete_hit_challenge_path(h), method: :delete do |f| %>
<%= f.hidden_field :hit_challenge_id, value: h.id %>
<%= f.submit "Delete" %>
<%end%>
</li>
<%end%>
<%else%>
<li>
<%= "Suite #{@hit_challenges.first.suite.suite_number}, #{@hit_challenges.first.title}:" %>
<%= link_to "Status", hit_status_path(@hit_challenges.first) %>
<%= link_to "Play", play_hit_challenge_path(@hit_challenges.first) %>
<%= form_for @hit_challenges.first, url: delete_hit_challenge_path(@hit_challenges.first), method: :delete do |f| %>
<%= f.hidden_field :hit_challenge_id, value: @hit_challenges.first.id %>
<%= f.submit "Delete" %>
<%end%>
</li>
<%end%>
<%end%>


Rest of the view:

<%if is_admin%>
<div class='create-challenges'>
<p>
<%=form_for :suite, url: create_suite_path(:game_id => @game.id) do |f| %>
<%= f.label 'Suite Number:' %>
<%= f.text_field :suite_number %>
<%=f.submit "Create" %>
<%end%>
</p>
<p>
<%=form_for :pitch_speed , url: create_pitch_speed_path(:game_id => @game.id) do |f|%>
<%=f.label 'Create Pitch Speed Challenge' %>
<%=f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
<%=f.label "Title:" %>
<%=f.text_field :title %>
<%=f.label "Min Speed:" %>
<%=f.text_field :min_speed %>
<%=f.label "Max Speed:" %>
<%=f.text_field :max_speed %>
<%=f.submit 'Create' %>
<%end%>
</p>
<p>
<%=form_for :prop_bet, url: create_prop_bet_path(:game_id => @game.id) do |f| %>
<%= f.label 'Create Prop Bet:' %>
<%= f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
<%= f.label "Title:" %>
<%= f.text_field :title %>
<%=f.submit "Create" %>
<%end%>
</p>
<p>
<%=form_for :hit_challenge, url: create_hit_challenge_path, :remote => true do |f| %>
<%= f.label 'Create Hit Challenge:' %>
<%= f.select :suite_id, options_for_select(@game.suites.map {|s| s.suite_number}), {include_blank: 'Suite number?'} %>
<%= f.label "Title:" %>
<%= f.text_field :title %>
<%=f.submit "Create" %>
<%end%>
</p>
</div>
<%= link_to "Edit Game", games_edit_path(@game) %>
<div class='challenge-lists'>
<div class='hit-list'>
<%=render 'hit_challenges_list', locals: {@hit_challenges => @hit_challenges, @game => @game} %>
</div>
<div class='prop-list'>
<%if @game.has_prop_bet%>

<h4> Prop Bets:</h4>

<%if @prop_bets.count > 1 %>
<% @prop_bets.each do |prop| %>
<li>
<%= "Suite #{prop.suite.suite_number}, #{prop.title}:" %>
<%=link_to "Status", prop_status_path(prop) %>
<%=link_to "Play", show_prop_bet_path(prop) %>
<%=link_to "Edit", edit_prop_path(prop) %>
<%= form_for prop, url: delete_prop_bet_path(prop), method: :delete do |f| %>
<%= f.hidden_field :prop_id, value: prop.id %>
<%= f.submit "Delete" %>
<%end%>
</li>
<%end%>
<%else%>
<li>
<%="Suite #{@prop_bets.first.suite.suite_number}, #{@prop_bets.first.title}:" %>
<%= link_to "Status", prop_status_path(@prop_bets.first) %>
<%= link_to "Play", show_prop_bet_path(@prop_bets.first) %>
<%=link_to "Edit", edit_prop_path(@prop_bets.first) %>
<%= form_for @prop_bets.first, url: delete_prop_bet_path(@prop_bets.first), method: :delete do |f| %>
<%= f.hidden_field :prop_id, value: @prop_bets.first.id %>
<%= f.submit "Delete" %>
<%end%>
</li>
<%end%>
<%end%>
</div>
<div class='pitch-list'>
<%if @game.has_pitch_speed %>
<h4> Pitch Speed Challenges </h4>
<%if @game.pitch_speeds.count > 1 %>
<%@pitch_speeds.each do |pitch| %>
<%= "Suite #{pitch.suite.suite_number}, #{pitch.title}:" %>
<%=link_to "Play", play_pitch_speed_path(pitch) %>
<%end%>
<%else%>
<%= "Suite #{@game.pitch_speeds.first.suite.suite_number}, #{@game.pitch_speeds.first.title}:" %>
<%=link_to "Play", play_pitch_speed_path(@game.pitch_speeds.first) %>
<%end%>
<%end%>
</div>
</div>
<p>
<li><%= link_to "Add Home Players", add_home_player_path(@game)%></li>
<li><%= link_to "Add Away Players", add_away_player_path(@game)%></li>
</p>
<p>
Total Hits:
<%=form_for @game, url: update_game_hits_path do |f| %>
<%=f.text_field :total_hits%>
<%=f.submit "Update Hits" %>
<%end%>
</p>
<%end%>


and finally my js file:

$(document).ready(function(){
$('.create-challenges').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
data: $(this).serialize()
}).done(function(response){
data = '<%= j(render partial: "hit_challenges_list")%>';
console.log(data);
$(".hit-list li").append(data);

}).fail(function(){
console.log('you fail in life')
})
})


I'm trying to create a a hit_challenge from that form and then try to append it to the list of hit_challenges as seen above. The partial works fine by itself and I can see the hit_challenges alright.

The ajax call goes through, the record is created but I can't figure out the append part. I think something is breaking while I'm trying to pass the newly created record data to the partial... what is appended is '<%= j(render partial: "hit_challenges_list")%>', it's like the ruby code inside doesn't work

Can it be because my partial is just too much? I tried passing locals in '<%= j(render partial: "hit_challenges_list")%>' but it made no difference. Btw I'm using rails 4.

EDIT:

Now I'm getting a weird syntax error, and I can't see what's wrong with the partial, I haven't changed anything and it works outside of that js method

SyntaxError (/Users/ddgs89/Desktop/Suite-Success/suite_success/app/views/games/_hit_challenges_list.html.erb:1: syntax error, unexpected '=', expecting keyword_end
...tput_buffer = @output_buffer; = = local_assigns[:];;@output...
... ^
/Users/ddgs89/Desktop/Suite-Success/suite_success/app/views/games/_hit_challenges_list.html.erb:1: syntax error, unexpected ']', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
...t_buffer; = = local_assigns[:];;@output_buffer = output_buf...
... ^):
app/views/games/_hit_challenges_list.html.erb:1: syntax error, unexpected '=', expecting keyword_end
app/views/games/_hit_challenges_list.html.erb:1: syntax error, unexpected ']', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
app/views/hit_challenges/create.js.erb:9:in
_app_views_hit_challenges_create_js_erb___1940717404351023775_70144770896860'
app/controllers/hit_challenges_controller.rb:8:in
create'

create.js.erb

$(document).ready(function(){
$('.create-challenges').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
data: $(this).serialize()
}).done(function(response){
data = '<%= j(render partial: "games/hit_challenges_list", locals: {@hit_challenges => @hit_challenges, @game => @game})%>';
console.log(data);
$(".hit-list li").append(data);

}).fail(function(){
console.log('you fail in life')
})
})
})

Answer

It's not working because you're trying to do server-side rendering in the client side. An approach is to have your controller render the partial and serve it to the client, but a better approach and the Rails way is to use remote: true option on your form_fors (not sure you're posting the right view as the create-challenges CSS class is not in the form you posted).

In your create action, you'd have:

def create
    game = Game.find(params[:id])
    suite_id = Suite.find_by(suite_number: params[:hit_challenge][:suite_id], game_id: game.id).id
    @hit_challenge = HitChallenge.new(game_id: game.id, suite_id: suite_id, title: params[:hit_challenge][:title])
    if @hit_challenge.save && request.xhr?
      respond_to do |format|
        format.json { render json: @hit_challenge}
        format.js
      end
    else
      redirect_to games_show_path(game)
    end
  end

In your create.js.erb

data = '<%= j(render partial: "games/hit_challenges_list")%>';
console.log(data);
$(".hit-list li").append(data);

Let me know if that works or other clarifications needed

UPDATE

Your final create.js.erb should look like this:

  data = '<%=j render(partial: "games/hit_challenges_list")%>';
  console.log(data);
  $(".hit-list li").append(data);

You should ensure that @hit_challenges and @game are being set somewhere in your controller, I removed the instance variable passed to the partial because it's redundant, if you're passing local variables to a partial, it has to be a symbol.