"Revitalizing DIVs with AngularJS controlled by Rails on the server side

I am using `ng-click' in AngularJS to delete a post from my database.

%table.table{"ng-controller" => "PostsCtrl"}
  %tr
    %th Title
    %th ....
    %th
  - @posts.each do |post|
    %tr
      %td...
      %td= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"

This code snippet is located in /app/views/posts/index.html.haml.

Here's the action for deleting a post:

 def index
   @posts = Post.all
 end

And here is the corresponding JavaScript code:

var app = angular.module('MyApp', ['ngResource']);
app.factory('Posts', function($resource){
 return $resource('/posts.json', {},{
    query: { method: 'GET', isArray: true },
    create: { method: 'POST' }
 })
});

app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});
app.controller("PostsCtrl", ['$scope', '$http', '$resource', 'Posts', 'Post', '$location', function($scope, $http, $resource, Posts, Post, $location) {

$scope.posts = Posts.query();
$scope.deletePost = function (post_id) {
    if (confirm("Are you sure you want to delete this user?")){
      Post.delete({ id: post_id }, function(){
        $scope.posts = Posts.query(); 

        $location.path('/');
        $scope.$apply();
      });
    }
  };
}]);

Although the record is successfully deleted from the database when I click the delete link, an error message appears in the JS console:

DELETE http://localhost:3001/posts/5620a8766f85ce82ce000002 406 (Not Acceptable)

Below is the Rails action associated with deletion:

  def destroy
    puts "test"
    respond_with @post.destroy!
  end

And here are the routes defined in routes.rb:

resources :posts do
  resources :comments
end

How can I resolve this error and refresh the table after deleting a record?

Thank you for your assistance.

EDIT:

Upon further investigation, it appears that AngularJS is sending the request as HTML when attempting to delete a post. This is evident from the output in the terminal:

Processing by PostsController#destroy as HTML
...
ActionController::UnknownFormat - ActionController::UnknownFormat:
...

Answer №1

It appears that the 406 error is signaling a problem with your backend's ability to provide the requested format, in this case HTML. One potential fix could be to explicitly specify the JSON format in your request like this:

Make sure to include .json after the :id

app.factory('Post', function($resource) {
    return $resource("/posts/:id.json", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});

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

Vue: the parent template does not permit the use of v-for directives

Upon creating a simple post list component, I encountered an error when trying to utilize the v-for directive: "eslint-eslint: the template root disallows v-for directives" How can I go about iterating through and displaying each post? To pass data from ...

Utilizing file uploading in combination with selected options for a streamlined experience

Currently, I am utilizing the jQuery FileUpload plugin created by BlueImp. The plugin utilizes x-tmpl for templating purposes. My aim is to populate a tags input field with options derived from a PHP variable. For now, I am experimenting by inserting place ...

Using ng-model with ng-repeat element

There is a situation where I need to replicate the <li> item and incorporate a dynamic model for writing click events. <ul class="flights trip1-list" ig-init="trip1_fare = 0"> <li ng-repeat="data in flt_det" ng-click="addUp($event)" ng ...

Is there a slider available for organizing Google Photos collections using JavaScript, Angular, React, or Vue?

I am excited to incorporate a vertical photo slider into my Angular/React app similar to the one seen on the Google Photos website. If you haven't seen it yet, here's a screenshot: of your google account, click this link to view. The slider org ...

Using AngularJS within a JavaServer Pages (JSP) document

Currently, I am in the process of developing a project that primarily consists of JSP pages. I am curious if it is possible to incorporate AngularJS into these existing pages. Additionally, I should mention that I am new to Angular and still learning abo ...

Navigate to a specific section within a div

I am currently developing a web chat application in next.js and have added an emoji picker button. However, when the button is clicked, the emoji menu only appears after scrolling down. I attempted to use scrollIntoView() but it did not work as expected. ...

Angular: the separation between two points on a map

I have two sets of location coordinates and I need to calculate the distance between them. I have researched and found some code examples in PHP, C++, C# and Java. Currently, I am working with Angular1 and I want to perform this calculation on the client ...

Guide on showing the message "loading" following multiple executions of JavaScript functions?

I recently customized a SharePoint list page for a new form. On this page, I've implemented a JS function that loads various documents from the document library into a Telerik RadComboBox component. However, when there are a lot of documents to load, ...

Send a request to a specific endpoint and display the retrieved data with Angular

Trying to access an endpoint with a GET request and display the data on my webpage <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4. ...

Sending a raw XML data through AngularJS's $resource service (version 1.2.x)

Trying to utilize AngularJS's $resource to send XML via POST to an API, I'm uncertain about how to pass the data that needs to be sent. This is my current setup: "Cart": $resource("http://........../api?ws_key=*********", { ws_key: ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Differences in row padding when transitioning from Bootstrap 3 to Bootstrap 4

One thing I've noticed is that when utilizing Bootstrap 3, the use of div.row would automatically create a vertical spacing between rows which was quite appealing. However, upon transitioning to Bootstrap 4, this automatic spacing seemed to disappear. ...

jQuery on-click event malfunctioning as expected

I'm currently developing a project that utilizes the GIPHY API to retrieve GIFs. Each time a search is performed, I am storing the search history as individual buttons which users can click on to view the results without needing to re-enter the search ...

Modify the characteristic of a moving component provided it meets the criteria

One of my functions, 'refreshDisplay', is designed to generate dynamic elements. However, there is a specific condition that needs to be met. In the 'src' attribute of the image, I need to check if the obj.picture.thumbnail starts with ...

calls to res.send and res.render

I'm currently trying to determine if it's possible to use res.send(data) and res.render('reports') simultaneously in my code. To provide more details, when I navigate to '/reports', on the server side I am executing a REST ca ...

Designing the autocomplete dropdown feature in Bootstrap UI

I'm currently developing an app that is utilizing AngularJS and Bootstrap, with the assistance of Bootstrap UI. Specifically, I am working on implementing the typeahead feature. However, I am facing a challenge in trying to ensure that the dropdown li ...

Trying to call the Wia class constructor without using the 'new' keyword will result in a TypeError

I'm having trouble running my code from a JSON file, as it's throwing this error message at me: TypeError: Class constructor Wia cannot be invoked without 'new'at Object. (/home/pi/wia-pi-camera/run-camera.js:3:25) 'use strict&apos ...

Is it advisable for a function to retain its asynchronous nature when utilizing the 'no-return-await' option?

Should the async function remain async if using return await is unnecessary? The use of return await inside an async function keeps the current function in the call stack until the awaited Promise is resolved, resulting in an extra microtask before resol ...

Discovering the applied column filter in Angular's UI-Grid

I am currently working with ui-grid and implementing server-side filtering. I make a request to the API for each column based on the filter value, with the default parameter being empty. var filterOptions = { filterBy: '&$fil ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...