Reputation: 41
I’m having trouble rendering a .js.erb from an action. The action triggers, and rails tells me that it’s rendering the js.erb, but the js never gets rendered and is evident from the console logs in the js not rendering to the browser’s console. I’ve tried a bunch of solutions online but can’t seem to find out why rails would be telling me this js template is rendering, but not have it actually render in the browser. What could I be missing?
Controller action
def dynamic_search
puts "WE ARE IN DYNAMIC_SEARCH"
puts params[:q]
client = HTTPClient.new
string = 'call to google places api'
@result = client.get_content(string)
@hash = JSON.parse @result
render "home/dynamic_search.js.erb", format: :js
end
Rails terminal output
Rendering home/dynamic_search.js.erb
Rendered home/dynamic_search.js.erb (Duration: 0.0ms | Allocations: 4)
Completed 200 OK in 479ms (Views: 0.7ms | ActiveRecord: 0.0ms | Allocations: 4613)
UPDATE:
Code that calls the action is below (not 100% correct but just testing the call at the moment using JQuery easy-autocomplete)
document.addEventListener("turbolinks:load", function() {
$input = $('*[data-behavior="autocomplete"]')
var options = {
url: function(phrase){
console.log(phrase)
return '/search/' + phrase
}
}
$input.easyAutocomplete(options);
});
Upvotes: 4
Views: 1313
Reputation: 29328
easy-autocomplete
is expecting dynamic_search
to return parsable data either (JSON or XML).
It is not actually running the js in "dynamic_search.js.erb" in the current context. This means that either the content of "dynamic_search.js.erb" needs to represent such an object after rendering or preferably the dynamic_search
action should just render it directly.
For Example (I will assume you want to use easy-autocomplete
with @result
)
def dynamic_search
puts "WE ARE IN DYNAMIC_SEARCH"
puts params[:q]
client = HTTPClient.new
string = 'call to google places api'
@result = client.get_content(string)
render json: @result
end
I am not sure what the @result
json actually looks like so you may need additional manipulation above or below.
Then the js could be:
document.addEventListener("turbolinks:load", function() {
$input = $('*[data-behavior="autocomplete"]')
var options = {
url: function(phrase){
console.log(phrase)
return `/search/${phrase}`
}
}
$input.easyAutocomplete(options);
});
Upvotes: 2