I am attempting to send a post request to fetch all events (Jams) and dynamically update the page using AJAX. My controller is receiving parameters in JSON format, and I want to respond with JS similar to using remote: true on a link or button.
Currently working with Rails 6.0.2.2
Here is an excerpt from my .js file:
const getJams = () => {
const mapCenter = map.getCenter();
const mapBounds = map.getBounds();
const token = document.getElementsByName("csrf-token")[0].content
fetch(window.location.origin + "/search", {
method: "POST",
headers: {
'Accept': "text/javascript",
'Content-Type': "application/javascript",
'X-CSRF-Token': token
},
body: JSON.stringify({
map_center: mapCenter,
max_lat: mapBounds._ne.lat,
min_lat: mapBounds._sw.lat,
max_lng: mapBounds._ne.lng,
min_lng: mapBounds._sw.lng
}),
credentials: "same-origin"
})
}
The method in the search controller where the data is processed looks like this:
def index
@jams = policy_scope(Jam)
respond_to do |f|
f.json do |f|
render json: {
jams: render_to_string(
partial: 'jams/jams',
formats: :html,
layout: false,
locals: { jams: @jams }
)
}
end
end
end
When executed, the server throws the following error:
Completed 406 Not Acceptable in 1ms (ActiveRecord: 0.0ms | Allocations: 889)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/searchs_controller.rb:7:in `index'
I'm trying to append elements inside my view within the search.js.erb file, where I have console.log("a");
, but that JS doesn't seem to execute as nothing appears in the console.
If anyone can offer assistance, I would greatly appreciate it.
Below is the content of the jams/_jam.html.erb partial file:
<% jams.each do |jam| %>
<div class="jam-card">
<%= image_tag jam.photo %>
<%= jam.status %>
<%= jam.user.first_name %>
<%= jam.music_style.music_style %>
<%= display_date(jam.start_date_time, jam.duration) %>
<%= jam.participants.count %>/<%= jam.max_participants %>
</div>
<% end %>