Executing a Ruby function via AJAX

I am fairly new to working with ajax, and I find myself in need of using it for my Rails application. Here is the function in my controller:

def check_code
  input = params[:input]
  code = params[:code]
  if input == code
    return true
  else
    return false
  end
end

Here is the JavaScript I have tried so far:

$('#submit_me').click(function() {
  var input_code = $('.input_code').val();
  var isValid = $.ajax({
        url: '/check_code/'+input_code+'/<%= @code %>',
        type: 'get',
        contentType: 'application/json; charset=UTF-8',
     });
  alert(isValid)
});

I am struggling to make this ajax call work. My goal is to invoke the controller function and capture the returned value in JavaScript. Any assistance on this would be greatly appreciated. Thank you.

Answer №1

You were on the right track! Just one more step to go. Remember, you need to add the "done" callback, which is a JavaScript function that will run when the Ajax request is successful:

Give this a try:

$('#submit_me').click(function(event) {
  event.preventDefault();
  var input_code = $('.input_code').val();
  $.getJSON('verify_code/'+input_code+'/<%= @code %>').done(function(data){
    alert(data);
  })
});

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

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

What happens when jQuery interacts with AJAX and encounters multiple hash values in an application

I have been incorporating ajax features into some of the web apps I've developed, typically using a single hash (e.g. example.com/products#shirts). But now I'm considering loading the "products" page through ajax as well. While I understand that ...

The unexpected postbacks caused by the ASP.NET MVC DropDownList appear to stem from JavaScript, catching me by surprise

In my MVC project, there's a standard form with a dropdown list. Each time I change the dropdown value, the entire page reloads due to a postback. This behavior is unexpected, and I want to prevent the dropdown from triggering a postback. Strangely, ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

How to transfer data from an HTML form to PHP using AJAX

I've encountered an issue while working on a simple application that consists of one HTML file communicating with a PHP page using AJAX. Take a look at my index.html below: <!DOCTYPE html> <html><head> <meta charset="utf-8"> & ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

Why are my variables resetting in Angular after ngAfterViewInit?

There seems to be an issue with my variables resetting after successfully using them in ngAfterViewInit(). I have a few @ViewChild and regular variables that are utilized or set in ngAfterViewInit. However, when certain events that I added post-initializa ...

What is the method for determining the number of arrays contained within a file?

I am working with a JavaScript file that looks like this: // main.js let array1 = ['first array']; let array2 = ['second array']; Currently, I have two arrays declared in my main.js file. Is there a method to determine the total ...

Dynamic Cascading Selection

I am new to using JQuery Ajax and I need help with creating a PHP script to read the subcategory list based on the selected main category. I have implemented a jQuery AJAX function in my asset_add.php file. <script src="jquery.min.js"></script> ...

Incorporating JSON information into highcharts for advanced data visualization

If I were to utilize JSON code from a specific website, such as this one: "", in order to incorporate it into my highcharts implementation. The data seems to consist of x_min, x_max, and price_data values. What would be the best approach for creating hig ...

Troubleshooting the issue of AJAX not successfully transmitting variables to PHP

let xmlhttpRequest; if (window.XMLHttpRequest) { xmlhttpRequest = new XMLHttpRequest(); } else { xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttpRequest.open("POST", "test.php", true); xmlhttpRequest.setRequestHeader("Content-typ ...

Unclear error message encountered with Rails server

Currently using OS X Sierra I'm managing a rails app with front-end and back-end components. The back-end is built on rails 4, while the front-end utilizes Angular. To run the server locally for development or testing purposes, I typically need to ha ...

Using jQuery or JavaScript, extract JSON data from Yahoo Pipes

Here is the JSON format that I receive from Yahoo pipes: {"count":3, "value":{ "title":"Freak count feed", "description":"Pipes Output", "link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=565sdf6as5d4fas ...

How can I identify the currently active partial in mvc3 framework?

Is there a way to dynamically determine which partial is currently active in the DOM so that I can apply CSS to it? Also, how can I create an anchor that allows users to copy and paste a URL to a specific partial? EDIT: Assume I have three links, where t ...

Consecutive AJAX requests triggered by previous response

While there are numerous resources available regarding making synchronous AJAX calls using deferred promises, my specific issue presents a unique challenge. The process I am attempting to facilitate is as follows: Initiate an AJAX call. If the response i ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...