What is the best way to send Rails variable to an AJAX response function?

When using AJAX, my code looks like this:

$.ajax({
   URL: '/update_profile_picture',
   type: 'POST',
   data: { username: 'exampleuser' },
   success: function(response){
       alert(response);
   },
 })

In my routes file (routes.rb):

post '/update_profile_picture' => 'avatars#update_avatar'

This is the method in the Avatar model (avatar.rb) that retrieves the profile picture based on the username:

self.update_avatar(username)
    Avatar.where(username: username).select('avatar').last
end

Inside the AvatarsController:

def update_avatar
    @username = params[:username]
    @result = Avatar.update_avatar(@username)
end

The question now is how to pass the @result variable back to the AJAX response function to alert the database selection result.

Answer №1

If you are looking to receive a response exclusively from this particular service, the recommended method is as follows:

def fetch_new_avatar
   @username = params[:username]
   render :json => Avatar.fetch_new_avatar(@username)

Answer №2

If you're looking to display text in your controller method, make sure to utilize the render :text function.

def show_result
    @name = params[:name]
    @outcome = Result.show(@name)
    render :text => "#{@username} has this outcome:- #{@result.inspect}"
end

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

parent component's triggering state

One interesting feature of my project is the modal wrapper which contains a react-modal npm module. The render method triggers the opening of the modal based on the value of this.props.isOpen. <ReactModal contentLabel="modal-big" className=" ...

Implementing Material-UI’s FlatButton and Dialog in ReactJS for dynamic TableRow functionality

I am working with Material-UI and have implemented a <Table> component. Each dynamically rendered <TableRow> in the <TableBody> needs to include a button (<FlatButton>) within one of the columns. When this button is clicked, a <D ...

Storing a combination of input fields and radio buttons in a single state: a guide

const [isChecked, setIsChecked] = useState(false); const handleRadio = (event: { currentTarget: { value: string } }) => { const isChecked = event.currentTarget.value === 'true' ? true : false; setValues({ checked: isChecked }); }; ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...

I'm struggling to figure out the solution for this error message: "Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined." Can someone please assist me with resolving this

Can you assist me? I am a beginner when it comes to javascript/React. I am currently following this tutorial https://github.com/Azure-Samples/js-e2e-client-cognitive-services and encountering the following error message: "Unhandled Rejection (TypeErro ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Even with minify and uglify plugins implemented, the React App remains unminified

I am facing a major issue with my reactjs app in production, as it exceeds 1.8 MB. I urgently need to reduce the size of the app. Below is the analysis from webpack: https://i.sstatic.net/skVfV.png Here is my webpack.config.js: const path = require( ...

Strategies for Resolving CORS Issues in React and Node/Express

Previously, my project was working fine with React in the frontend and a node/express server in the backend. However, I am now encountering a CORS error. The error message states: Access to fetch at 'https://dry-reef-22080.herokuapp.com/imageUrl&apos ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

I am facing an issue where I am unable to declare a variable in JavaScript for some unknown reason

My attempt to request data from an API built with JavaScript is encountering some issues. When I try to pass a variable through the URL, it doesn't get received. Even after trying to log the output using console.log, nothing appears on the console. I ...

What is the correct way to reset the styling of a web browser element, such as a <button>?

I have come across many sources advising me to reset HTML by manually resetting numerous individual properties, as demonstrated here: https://css-tricks.com/overriding-default-button-styles/ Another approach I discovered in CSS is simply using: button: {a ...

In JavaScript, a dropdown menu becomes active when clicked on and becomes inactive when clicking outside of it

My script is not functioning properly when I click outside of the drop-down menu of the "Sign in" button. View jsfiddle Demo $(document).ready(function() { $(".openmenu").click(function() { var X = $(this).attr('id'); if (X == 1) { ...

The sorting function is failing to produce the expected order of values

Currently, I am working on a feature to sort an array of objects based on user-selected values. Strangely, the function returns the same result no matter which case is executed. I have thoroughly checked each case and they are functioning correctly; howeve ...

Starting an AngularJS module without an HTML page may seem like a daunting task,

I am currently developing a browser extension project using AngularJS. Within the background.js file (which contains the code that runs in the background), I have created a module with a run block. var myExtensionModule = angular.module('myExtension ...

Tradebot for Node.js powered by Steam

I have created a Node.js Steam Bot using modules like steam user, steam trade, steamcommunity, and steam-tradeoffer-manager, among others. var username = "bot"; var password = "123456"; var steamguard = ""; var Steam = require('steam'); var St ...

Tips for storing information with JSON and PHP?

I am struggling with the following script, as I am new to JSON and trying to figure out how to store data in a MYSQL database. Can someone provide guidance on how to achieve this? Specifically, I need help with storing user login information from the Fac ...

Eliminate a string of words from a reply data - angularjs

When I console the response data from an angularjs json response, I found the following words: $rootScope.myData = res.data; //the above contains 1. Titles of Variations 2. In Sports 3. Going to Gym 4. My Car Runs Faster 6. Account Setup I need help remo ...

Mastering the art of utilizing generic types efficiently within Higher Order Component structures

My parent component (Grid) passes props to a higher-order component (hoc), let me show you: <QuickBooksTable itemList={quickBooksList} /> Here is the QuickBooksTable component: export const QuickBooksTable = withIntegrationTable(props: : WithIntegra ...

JS - reloading the location after a function has been carried out with a short delay

Currently, I am using a JS / AJAX script to update information in my table. After the script finishes running, I want to reload the page. Unfortunately, when using my current code, the page reloads instantly. Is there a way to add a delay of 3 seconds befo ...

Invoke the controller by clicking inside an iframe using AngularJS

I am attempting to attach an event to an iframe in order to trigger a function in the angular controller whenever any part of the iframe is clicked. My goal is to achieve this using either the jQuery lite provided by angular, or with pure javascript, depen ...