Error in Ajax Request for Incorrect URL in Rails Project

After attempting to remove an entry from my database by sending an URL via Ajax, I encountered a problem with my JavaScript code:

function disableService(id) {
  $.ajax({
    type: 'DELETE',
    url: '/app/delete_service/',
    data: { id: id },
    success: function() {
      // SOME CODE HERE //
    }
  });
}

The issue lies in the routes file, where I have set up a route to manage the request:

delete 'delete_service', to: 'company_services#destroy'

Even after trying to execute the request, it appears that Ajax is manipulating the URL and redirecting to a different one, despite me directly pasting the code into the console for inspection.

A discrepancy can be observed between the code's intended URL and the final requested URL, as seen in the provided screenshot.

https://i.sstatic.net/dcird.png

It's worth noting that while using GET works, POST or DELETE methods do not. Although GET may provide a temporary solution, it is not the optimal approach.

---------- UPDATE -------------

I have also attempted the Rails conventional method:

Routes.rb:

resources :company_services

However, this has resulted in the redirection of the original URL app/company_services/:id to app/company_services without the inclusion of :id.

https://i.sstatic.net/18MkQ.png

Furthermore, here are the routes associated with :company_services:

https://i.sstatic.net/oRtbe.png

Answer №1

Here is a suggested approach:

#=> routes.rb
resources :company_services
#=> DELETE /company_services/:id(.:format) # this is the format of your link

Next, update your AJAX script

function deactivateService(id) {
  var id = 45;
  $.ajax({
    type: 'DELETE',
    url: '/app/company_services/' + id,
    success: function(response) {
      // INSERT YOUR CODE HERE //
    }
  });
}

I hope this helps!

Answer №2

In an attempt to be helpful to others facing a similar issue, I have found the solution to my own question:

The issue stemmed from the fact that the controller handling the request had a redirect to app_company_services_path. My intention was to redirect to company_services after saving the changes, but I wasn't aware of how JavaScript requests function following a redirect.

My initial mistake:

def destroy
  # some code here
  redirect_to app_company_services_path
end

The correct approach is:

def destroy
  # some code here
  render json: { success: 'something here' }, status: 200
end

Subsequently, utilize JavaScript to handle the redirection instead of attempting a direct redirect from Rails.

Answer №3

Why not give this a shot?


 id = '45'
 url: '/app/company_services/' + id
 Alternatively, you could try the direct URL: 'app/company_services/45' for a quick test.
Hopefully this will be of assistance.

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

Assigning identical unique IDs to two transports in Winston

My project uses winston-js as a logger, and it's functioning well. However, I am now faced with the challenge of adding a unique log ID to each log line for debugging purposes. In my setup, I have two transports - 1) Console and 2) File. I want the ...

Error: Unexpected syntax error occurred due to the use of '===' operator

Click here for image descriptionError: There is a syntax error in line 7 of the file add.php Code: <?php require_once('db.php'); if ( !empty($_POST['name']) &&!empty($_POST['alias']) &&!empty($_POST[&apo ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Using ID attributes to compare JavaScript Objects and generate a distinct list within Angular/JS

I am working with the github API to retrieve an array of objects containing commit data. My goal is to extract a unique list of commitors and format it as shown below to create a graph: {"id":temp,"label":temp,"type": "number","p": {} } Here is the code ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

Repeated failures in the CodeIgniter JavaScript function

Currently I am developing a donation store using CodeIgniter. I have been focusing on implementing the cart functionality, and have created a small card to display the store items. The card allows users to add items to their cart using an AJAX request to p ...

Guide on Generating Dynamic JSON to Set and Retrieve Values for Forms and Displaying the Bound Values

I'm a beginner in Ionic 3 and I'm having trouble creating a page that redirects to another page without validation. I want to display the data on the new page, but it's not working. Please help! I also want to create a dynamic JSON object a ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

How can I store the result of an Ajax call in Ext JS for future reference?

How can I store the response of an ajax request for future reference? In the provided code snippet, I noticed an empty console log... Any suggestions on how to achieve this? var jsonData = ''; Ext.Ajax.request({ scope: this, ...

Using Vue.js transitions within a loop

I am facing an issue with a transition in Vue.js where only the leave transition is working and not the enter transition. Here is my code: <template v-for="(item, index) in imagesList"> <transition name="fade"> <div class="ctn"> ...

Is there a way to prevent the variable from being trapped in the first option when using an if/else if statement?

Below is my JavaScript code snippet: let x = Math.floor(Math.random() * 6) + 1); if (x == 1){ do this } else if (x == 2){ do that } else if.... and so on. Every time I run this code in a browser, only actions related to the {do this} section seem ...

The latest version of jQuery is causing issues with my XHR re-write functionality

After creating a straightforward re-write of the XMLHttpRequest object that functioned seamlessly with jQuery versions earlier than 2.2, I encountered issues with functionality when upgrading to version 2.2. Despite my efforts to pinpoint the exact cause b ...

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...

Having difficulty managing asynchronous functions with the useState hook in React

import React from "react"; import { UserContext } from "./../contexts"; import { removeStoredAuthData, storedAuthIsValid, storeNewAuthData, } from "./../utils/auth"; import { getUserInfos } from "./../api/userAuthen ...

Looking for assistance on how to access a JSON file in JavaScript without the need for servers

As I embark on my journey with JavaScript, a question has been lingering in my mind - is it possible to access a JSON file locally, without the need for servers like WAMP? My goal is to simply retrieve the data from a JSON file and display its contents o ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

Python/Selenium Issue: JS/AJAX Content Fails to Load when URL is Accessed

Currently, I am attempting to gather data from the following URL: The data that I am looking to extract is loaded dynamically, such as the Center Bore information. When accessing the link through a standard web browser, the content loads without any issue ...

Interactive button visual effect

I have a piece of code that currently plays audio when I click on an image. However, I am looking to modify it so that not only does clicking on the image play the audio, but it also changes the image to another one. Can anyone assist me with this? Here i ...

Updating or deleting query strings using JavaScript

My URL is structured as follows: http://127.0.0.1:8000/dashboard/post?page=2&order=title I am seeking a way to eliminate the query string ?page={number} or &page={number} Due to my limited knowledge of regular expressions, I am wondering if there ...