0

Using the rails cast http://railscasts.com/episodes/324-passing-data-to-javascript?autoplay=true

to pass a variable from my controller to javascript.

I have a button, when I click on it, i want it to show the number of upvotes.

Im using gon.

When I try to run it however ,my alert says the variable is not defined even though I set it in the controller

_source.html.erb

  <div class="panel-body">
  <%= include_gon(:init => true) %>
    <%=source.source %>
    <% @count = pluralize(source.upvotes.count,"upvote") %>
    <div id="count"><%= @count %></div>
    <%= button_to '+1', upvote_source_path(source), method: :post,remote: true %>

    <p><%= link_to "delete", [source.fact, source], method: :delete, data:{confirm: "are you sure?"} %></p>
  </div>

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Sourcemonkey</title>
    <%= include_gon(:init => true) %>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

sources_controller.rb ->upvotes action

def upvote
        @source = Source.find(params[:id])
        @source.upvotes.create
        gon.count = @source.upvotes.count
        respond_to do |format|
        format.js {render :js =>"upDateCount()"}
        format.html { redirect_to :none}
        end
    end

upvote.js.erb

function upDateCount(){
    alert(gon.count)
 }

routes.rb

Rails.application.routes.draw do
  # mount Ckeditor::Engine => '/ckeditor'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root to: "facts#index"

  resources :facts do
    resources :sources
  end

  resources :sources do
    member do
        post 'upvote'
    end
  end

  resources :upvote
end

Appreciate ideas, thanks

mogoli
  • 2,153
  • 6
  • 26
  • 41

1 Answers1

1

In this case it might be easier to pass upvote count to upDateCount

format.js {render :js =>"upDateCount(#{@source.upvotes.count})"}

and use there the argument instead of gon data.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • This works, thank you !!!! Im curious to know why this case is special and gon is not advised if you know? – mogoli Sep 09 '16 at 08:30
  • I don't use `format.js`, I tend to respond with data, not scripts, which is why I don't know that for sure. I suppose that scripts rendered by controllers are evaluated in a different context, than static scripts. – mrzasa Sep 09 '16 at 11:36
  • Thanks for the explanation, Im starting out with rails, so appreciate the insight – mogoli Sep 09 '16 at 14:57
  • I would suggest you not to render js, but send json data in ajax responses. – mrzasa Sep 09 '16 at 15:26