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

Despite a valid entry from a list, the controller is receiving null values in MVC 4 with AJAX integration

I am currently developing a "create" form that includes fields for OriginAirportID and DestinationAirportID. Currently, when a user inputs a string of letters into these fields, an AJAX request is triggered to retrieve data in JSON format. This data is th ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Utilizing AJAX to call a partial view

Here is the snippet of code showing my ajax call to a partial view after some processing: function fetchData(data) { $.ajax({ url: "/Orders/DraftOrderDetailsLineItems", type: 'GET', cache: false, dataType: 'html', d ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

ng-grid defines different cellClass based on the value of the field

I am currently using the ng-grid and I want the column to display in a different color based on different values. I have tried, but not succeeded so far... $scope.gridOptions = { ........ columnDefs: [ { field: "status", displayName: "St ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Is it possible to merge createStackNavigator with createBottomTabNavigator for enhanced navigation functionality

Current Situation : My app currently has three tabs for navigation (School, Admin, Family); I am now facing a challenge as I want to add additional screens that do not require tabs for navigation. These screens will be accessed using this.props.navigati ...

Connect the jQuery UI droppable feature to the Lift ajax handler

I'm currently developing a web application using Scala / Lift and I want to enhance user experience by adding drag and drop functionality. However, I am unsure how to integrate jQuery with Lift for this purpose. At the moment, I have a draggable div ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

What is the best method for displaying a table using a JSON array?

I have a JSON array that I want to display in a table using React boxes: [ { id: 1, color: "red", size: "small" }, { id: 2, color: "blue", size: "medium" }, { id: 3, color: "green", size: "large" }, { id: 4, color: "yellow" ...

Printing incorrect value in $.ajax call

I came across this code that I have been working on: var marcas = { nome: '', fipeId: '' }; var marcasVet = []; var select; $.ajax({ dataType: "json", url: 'http://fipeapi.wipsites.co ...

Validation of forms using Javascript

I currently have an HTML form with JavaScript validation. Instead of displaying error messages in a popup using the alert command, how can I show them next to the text boxes? Here is my current code: if (document.gfiDownloadForm.txtFirstName.value == &ap ...

Verify whether the div contains a specific class before triggering the animation

I'm attempting to create an animation following a user interaction with the Owl Carousel drag feature. The issue I'm encountering is that the code referencing $(this) does not recognize the .nav-item element with the .active class. Any insights ...

An issue with Nuxt.js causing body parameters to not be passed successfully while using this.$http.post

I've encountered an issue where using the @nuxt/http this.$http.post and this.$http.patch methods is causing problems with parsing body parameters during posting. Strangely, it used to work perfectly fine before, leaving me unsure of where to even beg ...

Having difficulty inserting an image with style="background-image:url(' ')" in Rails from the database

Hi everyone! I am new to both Rails and Stack Overflow, and I would really appreciate it if someone could guide me here. I am currently working on a test site that resembles a personal blog. It's mainly for showcasing one user's portfolio. In t ...