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

Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load. In addition to disabling buttons, I also aim to deactivate all links on th ...

The success:function() is not being triggered in the Ajax response with jQuery version 1.8.3

My code is not calling success:function() in the Ajax response when using jQuery 1.8.3, but it works perfectly with jQuery 1.4.2. Here is the code snippet: <script type="text/javascript"> $(document).ready(function(){ $("#usn").on('keyup&a ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...

Utilizing API calls within a loop using AngularJS

I need to execute a series of APIs in a loop, but I want the second loop to start only after receiving the result from the last API call in the first loop. How can I achieve this? for(var i=0; i<array.length; i++ ) service.getfunction(array[i]).t ...

Searching for matching strings in jQuery and eliminating the parent div element

Here's an HTML snippet: <div id="keywords"> <div id="container0"> <span id="term010"> this</span> <span id="term111"> is</span> <span id="term212"> a</span> <span ...

The issue of Ajax failing to send POST variables to a specified URL

I'm looking to dynamically populate related dropdowns with data fetched from the database. On my HTML page, I have a select element with the id 'fontes' and another one with the id 'cargos'. Below is the jQuery code snippet that I ...

Website search bar - easily find what you're looking for

I've tested this code and it works well on the basintap page. However, I'm interested to find out how I can search for something when I'm on a different page instead? <?php $query = $_GET['query']; $min_length = 2; if(strlen($ ...

Struggling to make the DataTables.net Bootstrap 5 example function properly

I'm currently working on familiarizing myself with the styling example for Datatables.net using Bootstrap 5, which can be found at https://datatables.net/examples/styling/bootstrap5.html. I've followed the code provided in the example closely, bu ...

Utilizing CDN script with Shopify: A guide to optimization

I am currently utilizing VueJs in the development of a Shopify theme using Shopify Cli and Store 2.0. To incorporate Vue, I initially attempted to install it through a CDN script within my theme.liquid file. <script src="{{ 'vue.global.js&apos ...

Integrate my API with HTML using J.Query/Ajax technology

Finally, after much effort, I have successfully created a JSON java API. My API design is simple and based on Interstellar movie details: { "title": "Interstellar", "release": "2014-11-05", "vote": 8, "overview": "Interstellar chronicl ...

Issue with Bootstrap tab display of content

I'm having trouble with the tabs in my page. When I click on each tab, the content doesn't display correctly. Here is my code: <div class="w470px exam" style="border: 1px solid #ddd; margin-top: 30px;"> <ul id="myTab" class="nav nav ...

I am facing an issue where reducing the size of the renderer is causing my click events to be offset. What steps can I

At the moment, my rendered model (which is grey in color) stretches across the entire width of the html page with the mesh centered within that width. I want to reduce this width but when I do so, the click event on the model seems to be misaligned. Three. ...

Switching the cursor to an image when hovering over an element is causing inconsistency in hover events triggering

Currently, I am attempting to implement an effect that changes the cursor to an image when hovering over a text element and reverts back to the normal cursor upon leaving the text element. However, this functionality is not working as expected when using R ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

display saved data from ajax request

I've been working on saving data and files using ajax. Following a tutorial (link), I managed to successfully save the data in the database and the image files in the designated folder. However, I'm facing an issue where the success or error mess ...

What is the best way to stop a current action when a new action is initiated?

My current setup involves an action creator that performs a costly calculation and triggers an action when the user inputs data in real-time. The challenge arises when multiple inputs are entered, as I want to avoid running the entire expensive calculati ...

What is the solution for fixing the "Invalid Element Type" error?

Hey there! I'm currently working on creating a Twitter clone using React, but I've run into an error that's giving me some trouble. The error message reads: "Element type is invalid: expected a string (for built-in components) or a class/fu ...

Limit the rotation of jQuery and CSS3 elements to always turn in a clockwise direction

Utilizing the jQuery transit plugin, I am rotating a block element with 4 navigation controls. Each time a nav item is clicked, the block rotates to the specified custom data attribute of that nav item - either 0, 90, 180, or 270 degrees. While I have suc ...

Ways to emphasize the chosen row within angular js 4

Today, I am exploring an example to understand how data can be passed from a parent component to a child component and back. Below are the files that I have used for this example. I have included both the HTML and TypeScript files for both the parent and ...

Maintain hover effect of main menu on sub-menu in CSS3 flip dropdown menu

Check out the fiddle I created for my query https://jsfiddle.net/e7te8hf1/ <section id="action-bar"> <div id="logo"> <a href="#"><img src="img/logo.png"></a> </div><!-- end logo --> <nav class="navbar navigat ...