Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some assistance in finding a better approach.

feed_controller.rb

def index
 @hashtags = hashtag_refresh
end

def hashtag_refresh
 Hashtag.order('created_at DESC').limit(10).uniq
 respond_to do |format|
  format.js
end
end

feed\hashtag_refresh.js.erb

 $('.trends_li_container').html("<%= escape_javascript(render('feed/shared/hashtag_list')).html_safe %>");

routes.rb

get 'feed/hashtag_refresh', to: 'feed#hashtag_refresh'

hashtag_autorefresh.js

//Refresh Hashtags Partial
$(document).ready(function (){
    setTimeout(refreshHashtag, 60000)
});

//Calls action refreshing the partial
function refreshHashtag() {
    $.ajax({
        url: 'feed/hashtag_refresh',
        type: 'GET',
        dataType: 'script'
    })
}

feed/shared/ folder _hashtag_list.html.erb

feed/ controller folder hashtag_refresh.js.erb

Server Development Log

  Started GET "/feed/hashtag_refresh?_=1462210930323" for 127.0.0.1 at 2016-05-02 13:45:05 -0400
    Processing by FeedController#hashtag_refresh as JS
      Parameters: {"_"=>"1462210930323"}
      User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 5]]
      Rendered feed/shared/_hashtag_list.html.erb (0.0ms)
      Rendered feed/hashtag_refresh.js.erb (11.5ms)
    Completed 200 OK in 50ms (Views: 47.5ms | ActiveRecord: 0.0ms)

Answer №1

Consider updating your refreshHashtag() function with the following changes:

// Function for refreshing the hashtag content
function refreshHashtag() {
    $.ajax({
        url: 'feed/hashtag_refresh'
        type: 'GET', //POST
        dataType: 'script'
    })
}

Answer №2

It seems like the issue lies in the return value of hashtag_refresh. Instead of returning a collection of Hashtags, it is actually returning the result of respond_to, which is unknown to me :P

To fix this, you can update your controller as follows:

def index
  hashtag_refresh do |hashtags|
    @hashtags = hashtags
  end
end

def hashtag_refresh
  yield Hashtag.order('created_at DESC').limit(10).uniq
  respond_to do |format|
    format.js
  end
end

For your JavaScript code:

// Refresh Hashtags Partial
$(document).ready(function (){
  setInterval(refreshHashtag, 60000)
});


// Calls action refreshing the partial
function refreshHashtag() {
  $.ajax({
    url: 'feed/hashtag_refresh.js',
    dataType: 'javascript'
  })
}

It's recommended to use setTimeout instead of setInterval for recursive calls in JavaScript to avoid running indefinitely if not canceled manually. Here's an updated version:

//Refresh Hashtags Partial
$(document).ready(function (){
  (function refreshHashtag() {
    $.ajax({
      url: 'feed/hashtag_refresh.js',
      dataType: 'javascript'
    }).then(function() {
      setTimeout(refreshHashtag, 60000);
    });
  })();
}); 

I hope this helps resolve your problem :)

UPDATE

If you encounter the error ActionController::UnknownFormat, it indicates that Rails does not recognize the format js or the mime type text/javascript. You can add some configuration in

config/initializers/mime_types.rb
to address this:

config/initializers/mime_types.rb

# The RFC standard mime type for javascript
Mime::Type.register "application/javascript", :js

# The legacy but widely used mime types for javascript
Mime::Type.register "text/javascript", :js
Mime::Type.register "application/x-javascript", :js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of appending request URLs in the $.ajax function

Can anyone explain why jQuery.ajax() adds a parameter to the URL? I enabled cache, but it's still not working as expected. The console logs are not showing up and the request URL is being modified with &_=1396146406542. How can I remove this add- ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

Issue with dropdown list removeClass function

I am encountering an issue with the Jquery dropdown list click function. The addClass method is working properly, but the removeClass method is not functioning as expected. When I click on the dropdown list, it does not hide. Here is a live demo: http://j ...

Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller: public class Controller extends HttpServlet { private Chooser chooser = Chooser.INSTANCE; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExcep ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

A step-by-step guide on accessing and displaying local Storage JSON data in the index.html file of an Angular project, showcasing it on the

I am facing an issue with reading JSON data from localStorage in my Angular index.html file and displaying it when viewing the page source. Below is the code I have attempted: Please note that when checking the View page source, only plain HTML is being ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Troubleshooting React: Child Component Fails to Render

Currently, I am enrolled in a React course and deep diving into the lifecycle methods of React. Through implementing componentDidMount, I have successfully made API calls and set the state accordingly. However, I am facing an issue with displaying images ...

Personalized parallax design

I am in the process of developing my own custom parallax plugin to allow me to control the direction in which items transition off the screen. However, I am currently facing a challenge in ensuring that regardless of how a user scrolls or the size of the w ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Responsive design in Android does not function as intended

My goal is to create a responsive design for my website, but I am encountering issues with importing the CSS files into the HTML. When I try to view the site in both the Windows version of Chrome and the Android version, all I see is a white screen. I am c ...

What are the steps to effectively incorporate Jquery Ajax in a success function?

Is there a way to successfully implement Jquery Ajax in this scenario? When I click on Getcat it works, but when I click on Cat 1, Cat 2... it fails. Why is that? I'm still learning the basics here, any help would be appreciated. Thanks! This is ca ...

Does vite handle module imports differently during development versus production?

I am currently working on incorporating the jointjs library into a Vue application. It is being declared as a global property in Vue and then modified accordingly. Below is a basic example of what I am trying to achieve: import Vue from 'vue'; im ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Can minification of JS be achieved in a Jekyll environment?

Currently, I am in the process of developing a project with Jekyll and one of the requirements is to minify HTML, CSS, and JS. I was wondering if Jekyll has built-in features for JS minification. It may seem like a simple question, but since I am new to ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...