Encountered an error "Not Found" when attempting to establish an AJAX connection between Javascript and Rails

I'm having an issue with a simple Rails controller method. When I call it from JavaScript as an AJAX method, I get the error message "Not Found" in the JavaScript error log, even though the method works fine when accessed directly in the browser. What could be causing this?

Here's the output I see in the browser console:

"jqXHR: [object Object]" application.js:3069
"textStatus: error" application.js:3070
"errorThrown: Not Found"

Thank you for any insights!

Coupons_Controller:

def get_value()
    #coupon_name = params[:param1]
    #@coupon = Coupon.get_price(coupon_name)

  #respond_to do |format|
      #format.js { render :layout=>false }
      #render text: "17.8, true";
      render text: "OK";
    #end
  end

Javascript script method:

function validateDiscountCouponIDAjax( sec1, sec2 ) {
                    if( typeof sec1 === 'undefined' || typeof sec2 === 'undefined' ){
                sec1 = 2;
                sec2 = 3;
            }

                    $.ajax({
                            type: 'POST',
                            url: 'http://localhost:3000/coupons/',
                            //data: $('discount_coupon_id').serialize(),
                            success: function(resp) {
                                    if (resp === 'OK') {                                        
                                        console.log('Validation ok');
                                        showMessage( true, 'Discount coupon validated!' );  
                                    }
                                    else {
                                            console.log('Response error: ' + resp);
                                            //$('#password-dialog-error').text(resp);
                                    }
                            },
                            error: function( jqXHR, textStatus, errorThrown ) {
                    var seconds = sec1 + sec2;
                    sec1 = sec2;
                    sec2 = seconds;

                    console.log('jqXHR: '+jqXHR);
                    console.log('textStatus: '+textStatus);
                    console.log('errorThrown: '+errorThrown);

                    var reconnectInterval = setInterval( function() {
                        changeMessage( false, 'Connection error. Trying to reconnect in ' + seconds + ' seconds.', false );
                        seconds--;

                        if( seconds <= 0 ) {
                            clearInterval( reconnectInterval );
                            hideMessage( 'fast' );
                            validateDiscountCouponIDAjax( sec1, sec2 );
                        }
                    }, 1000 );
                            }
                    });
            }

ADDED: I found error in JS class:

No route matches [POST] "/coupons"

Why such error?

ADDED 2: SOLVED! OK solved:), I was using GET in Route.rb, but AJAX was trying to do POST:). After changing both to GET , it works:)

Answer №1

Issue Resolved:

The problem was identified as a mismatch in request methods for the JS AJAX method and the Route.rb URL.

...
$.ajax({
type: 'POST',
url: 'http://localhost:3000/coupons/',
...

However, in Route.rb, the URL was defined to accept GET requests only.

get 'coupons' => 'coupons#get_value', :as => :coupons

The solution involved updating both places to either GET or POST method based on requirements.

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

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Is it possible to define key strings as immutable variables in JavaScript/Node.js?

Having transitioned from the world of Java to working with Node.js + AngularJS for my current project, I have encountered a dilemma. There are certain "key Strings" that are used frequently in both client and server-side code. In Java, it is common practi ...

Unable to upload a file to an email using the mandrillapp JSON API

Having trouble sending an email with an attached document via the Mandrillapp JSON API using the method send-template in JavaScript. The email sends successfully, including images attached to the images array. However, documents sent in the attachements ar ...

What is the best way to fetch images from a JSON object in a React application?

I have been trying to load images from an array of objects in React, but I keep encountering a "module not found" error. This issue has been frustrating me for the past couple of days. Can someone please help me troubleshoot this problem or provide some su ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

The data type 'string[]' cannot be assigned to the data type 'listData[]'

I'm currently developing a flexible component that allows the list view to be utilized by different components. However, the challenge arises from the fact that each component has a different data format. In my project, I'm unable to use type any ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

Tips for wiping clean and restarting data in a modal?

After closing and reopening this modal, both the old information and new data remain. I aim to reset everything within the modal, wiping out details from both the header and body. Expected scenario - Actual situation - Code- .html.erb file <div cla ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

How can I show a tooltip in vuetify when a button is disabled?

I am currently using the button and tooltip components in my Vuetify project. I am trying to find a way to only display the tooltip when the button is disabled, but I'm having trouble figuring out how to do it correctly. Right now, the tooltip only a ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...

Adding scripts to a PartialView in MVC using Jquery's append function

My issue is with a JavaScript function that appends a PartialView into a div. Everything seems to work correctly, except for the fact that the PartialView contains some scripts enclosed within <script></script> tags. As a result, when these dyn ...

Maintaining Existing Filters and Incorporating Additional Filters in React/Next.js Data Filtering

I'm currently facing a challenge with filtering data in React/Next.js. The issue I'm encountering is that whenever I set a new filter, the previous filters get removed. For instance, if a user performs a search, it works fine but the tag filters ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Is it possible to dynamically populate a dependent select box using Jinja variables?

I am currently using Flask with Jinja2 templates, and I need assistance in creating dependent select boxes. How can I achieve this using Jinja2 or a combination of JavaScript and Jinja2 variables? For example: On the Python side: @app.route('/&apos ...

How should I proceed if I encounter an npm error stating that cb() was never called?

Hey everyone. I keep encountering an issue with npm whenever I attempt to install packages. I am receiving the following error message: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <h ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...