I used to follow coderwall tutorial in ajax but I got ActionController::UnknownFormat when I open to new tab the following link <%= link_to 'Link Name', fetch_items_path(:cat_id => cat.id), :remote => true %>. What's wrong with this? Thanks!
In additional, when I click the link it doesn't respond to anything.
Here is the
Controller:
def from_category
@selected = Item.find(params[:cat_id])
respond_to do |format|
format.js
end
end
Views
index.html.erb
<%= link_to 'Link Name', fetch_items_path(:cat_id => cat.id), :remote => true %>
_items_list.html.erb
<% items.each do |item| %>
<div class="item_box">
...
</div>
<% end %>
item_grid.html.erb
<div>
<div id="items_grid" >
<%= render partial: 'items_list', locals: {items: items} %>
</div>
</div>
from_category.js.erb
$("#items_grid").html("<%= escape_javascript(render partial: 'items_list', locals: { items: @selected } ) %>");
The likelihood is that you're sending a json
request, which isn't covered by your respond_to
block.
You can see this by doing the following:
respond_to do |format|
format.json
format.js
end
Alternatively, you could also try:
<%= link_to 'Link Name', fetch_items_path(:cat_id => cat.id), remote: true, format: :js %>
If either of these work, it essentially means you're sending a JSON request, which won't be handled. The patches above should resolve it if it is the case.
--
Secondly, when you mention
"I open to new tab"
You realize that Ajax isn't meant to work synchronously, right? This means that it's not meant to load "in order" of the entire page. It has to be loaded along-side the page itself. To do this, you need to invoke it from the page onto which it has been embedded.
--
Finally, you should be aware of the JS console
in your browser.
For Chrome and Firefox, you can access this by right-clicking, selecting "Inspect Element". This will bring up the "Developer Console", from which you'll be able to see what's happening with the javascript:
Now, the importance of this for your case is simple. You mention "nothing happens" when you click the link. There are several potentialities for this:
jquery-ujs
enabled (which is what Rails uses to get the likes of remote
workingEither way, you'll be able to see what's going on by clicking onto the Developer Console and examining the networking
tab. Notice when you click the link - does it create a new request? If not, you'll have to add the jquery-ujs
gem to your Application.js file, else there's an issue with the script on the server.
After analyzing, I've got the wrong part of the code. It's regarding to routing.
Instead:
get "/fetch_items" => 'items#from_category', as: 'fetch_items'
I changed to:
get "fetch_items"
and its working properly now.