This issue has he pretty baffled. I have a simple form that has a remote: true
method. Im simply trying to get the users input from the form and send it to javascript for further use.
/main/app/controllers/queries_controller.rb
In the controller when I use pry all the values I expect to be there are there, but when it comes to gon value being send to javascript its always undefined
.
def index
search_term = params[:query]
@stats = Query.api_response(search_term)
gon.stats = @stats
respond_to do |format|
format.js
format.html
end
end
/main/app/models/query.rb
class Query < ApplicationRecord
def self.api_response(term)
url = "https://api.ritekit.com/v1/stats/history/#{term}?tags=&client_id="
api = "1234567890123456789"
return HTTParty.get(url + api)
end
end
views/shared/_form.html.erb
<%= form_tag queries_path, method: :get, remote: true do %>
<%= text_field_tag :query %><br>
<%= submit_tag 'Search' %>
<% end %>
/main/app/views/queries/index.js.erb
This value is undefined when sent to the console.
$(document).ready(function(){
console.log(gon.stats)
});
/main/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html lang="en">
<head>
<%= include_gon %>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.19/api/sum().js"></script>
<link href="https://fonts.googleapis.com/css?family=Righteous" rel="stylesheet">
</head>
I have also tried
<%= content_tag "div", id: "foobar", data: {value: @stats} do %><% end %>
and got undefined
as well when I used jQuery to access it.
Im really stumped on this one, and its bothering me because its been a few days and i'm still not getting intended result. Any help will be very appreciated.
As far as I know gon
does not allow to that. Or at least there is no out-of-the-box mechanism for updating gon
variable via ajax request. They have gon.watch
, but it is for other use cases.
And I think you don't need it. When your server respond with .js.erb
template you already have access to data in javascript. You can access @stats
variable as <%= @stats %>
. No need to use gon
there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.