Links with data-remote="true" not processing as JSON

11,257

Solution 1

Make sure that you have installed the jQuery UJS Plugin:

Add this to your gemfile:

gem 'jquery-rails', '>= 1.0.3'

And then run:

bundle install
rails g jquery:install

Solution 2

I had a similar issue: I expected a remote link to be processed as JS request but Rails somehow was processing it as HTML.

The problem is we don't specify a format and then Rails could choose any of the formats depending on the server configuration.

TL;DR; Specify the request type when using remote:

<%= link_to "Get Books", "/books", data: {remote: true, type: "script"} %>
Share:
11,257
Streamline
Author by

Streamline

Updated on June 19, 2022

Comments

  • Streamline
    Streamline almost 2 years

    I am testing creating a link_to with :remote=> true to get the ajax remote link handling.

    <%= link_to "Get Books", "/books", :remote=> true %>
    

    The helper for rails3 resolves the code correctly in the view and I get as source:

    <a href="/books" data-remote="true">Get Books</a>
    

    And I have the default javascript included:

    <%= javascript_include_tag :defaults %>
    

    And the source head resolves as:

    <script src="/javascripts/jquery.js?1302296105" type="text/javascript"></script>
    <script src="/javascripts/rails.js?1302139751" type="text/javascript"></script>
    <script src="/javascripts/application.js?1305999509" type="text/javascript"></script>
    

    And in the controller I have:

    respond_to :html, :json
    

    However when I click the link it loads as regular link, not ajax and on the server log:

    Processing by BooksController#index as HTML

    What am I missing?

  • Streamline
    Streamline almost 13 years
    Thanks! - That was certainly the problem. I also had to run "rails generate jquery:install" and comment out a previously added "config.action_view.javascript_expansions[:defaults] = %w(jquery rails)" in config/application.rb- I think I could change it manually to include jquery_ujs but commenting out that line seems to fall back to the correct default "defaults". All working now!
  • oowowaee
    oowowaee about 7 years
    I had a similar issue where I had stupidly overwritten the data-type attribute. Renaming the data attribute solved it.