Can a JavaScript variable be passed to the create function of a controller in Rails?

In my current project, I am working with Rails 4 which involves a User model and a Record model. My goal is to pass two javascript variables to the create method of the controller.

To achieve this, I have set up an AJAX call:

var funds = $('input#test').val();

var weight = $('input#result').val();

$.ajax({
  url: "/final",
  type: "POST",
  data: {
       funds: funds,
       weight: weight,
  },
  complete: function(){
       console.log('Congrats');
  }
});

I have defined the route in my config file like so:

post '/register' => 'users#create'

Here is the corresponding controller code:

    def create
        @user = User.new(ticket_params)

        @funds = params([:funds])
        @weight = params([:weight])

        respond_to do |format|
          if @user.save
            format.html { redirect_to @user, notice: 'User was successfully created.' }
            format.json { render :show, status: :created, location: @user }

            Record.create(fund: @funds, weight: @weight)

          else
            format.html { render :new }
            format.json { render json: @user.errors, status: :unprocessable_entity }
          end
          format.js
        end
      end

However, I encountered a 400 bad request error.

I want to ensure that the variables funds and weight are passed correctly to the create method of the controller for further use.

After some investigation, I found out that changing the AJAX call verb from POST to GET resolves the error message. But then, when creating the User, the controller claims that the parameters are empty, even though I verified them.

How can I effectively send javascript variables to the create method?

Below is the error message recorded in the network console of my browser:

ActionController::ParameterMissing in UsersController#create

param is missing or the value is empty: user


Application Trace
app/controllers/users_controller.rb:109:in `user_params'
app/controllers/users_controller.rb:40:in `create'

The error displayed in the console is as follows:

POST http://localhost:3000/final 400 (Bad Request)
m.ajaxTransport.send @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
m.extend.ajax @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
(anonymous function) @ VM2175:27
m.event.dispatch @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5
m.event.add.r.handle @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5

Answer ā„–1

To begin, check that you possess:

  • gem 'jquery-rails' within your Gemfile
  • //= require jquery in your application.js

Next, ensure that your data does not contain an unnecessary comma:

$.ajax({
  url: "/register",
  type: "POST",
  dataType: "json",
  data: {
       authenticity_token: $('meta[name=csrf-token]').attr('content'),
       funds: funds,
       weight: weight
  },
  complete: function(){
       console.log('Congrats');
  }

});

You can include multiple parameters within the ajax data section.

Please let us know if you require further assistance.

Answer ā„–2

After much searching, I finally cracked the code to my issue.

The main challenge was tackling the _form.html.erb file for my User model. Specifically, I was working on a webpage where users fill out a form. My goal with an AJAX call was to pass parameters to the create method in my controller so that I could utilize them within said method.

However, initiating an AJAX call triggers the entire method to run. In my controller, I discovered that the initial line of code fetches the ticket_params, which should contain the user-inputted information from the form. Yet, since the form hadn't been submitted (the user had just inputted data triggering an AJAX call), these parameters were empty.

To resolve this, instead of using an AJAX call to transmit parameters to the create action, I opted to introduce two additional attributes within the User model and utilized two more hidden_field elements to store the javascript variables weight and funds. When the user eventually clicks the submit button, the parameters are seamlessly transferred to the create method, enabling me to retrieve them as needed using the snippet @user = User.new(ticket_params).

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

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

The loading of the Bootstrap tagsinput has encountered an error

I am facing an issue with my Django application where tags are not loading properly in an input field using jquery. It seems like the application is unable to locate the bootstrap-tagsinput.css and bootstrap-tagsinput.js files. Can anyone provide guidance ...

Insert newly added rows' values into the database dynamically

Hello there, I'm currently working on a PHP form that needs to dynamically add a table row when the "Add" button is pressed. I'm using a for loop to save the values, but I'm running into an issue where the data is not being saved into my dat ...

Creating an API for a model with a linked attribute

Iā€™m trying to figure out how to display data from a model that references another model's attribute. Specifically, I have a Driver model with a "state" attribute that should reference a separate State model with a "name" attribute. While I understan ...

What is the best way to transfer a user query to a Next.js API?

I've integrated the Listen Notes podcast-api into my Next.js api routes. My goal is for the user query entered in a form on the front-end to trigger actions in the Next.js api. For example, if a user types "history", I want the api to search for podca ...

Using the combination of JQuery DataTable, AJAX calls, Struts2 framework, and JSON data

Hello everyone. I currently have a web application that is built on java+struts2. Within one of my webpages, I have implemented JQuery tabs and in one particular tab, I am attempting to populate a table with a large number of records sourced from a databas ...

Discovering digits within a given text using a specific pattern and modifying them using JavaScript

I have a series of text inputs containing numbers with a specific pattern throughout the text. I would like to identify all numbers with this pattern, recalculate them, and replace them in the text. .... val="2xf" ......... vc="2.6xf" ...... value= ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

The next column featuring a dropdown menu

My goal is to make this sketch operational. The red elements in the sketch need to be programmed. Currently, I am using angularJS and bootstrap with the following code: <div class="col-md-6"> <div class="form-group"> <label&g ...

Working with jQuery conditionals to manipulate JSON data

I'm working with JSON data that includes a field like this: "first_date": "2015-06-02" Using jQuery, I want to achieve something like this: if( valueOfFirstDate.substring(5, 6) == "06" ){ //change 06 to "June" } Can anyone guide me on how to e ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

I'm curious about the Javascript pattern I saw in D3s Pie Layout - can anyone shed some light

While delving into the source code of D3, I stumbled upon an intriguing pattern in pie.js. It seems that after being defined as an "inner function," new "methods" are added to it before being returned as a hybrid function/object combination. Can anyone she ...

Error code 2769 in Typescript occurs when attempting to transfer process information to the data state in order to utilize it within a modal

I'm encountering an issue while trying to pass a process to a setData state from a .map function in order to display it on a modal. The error message I'm receiving is: "No overload matches this call. Overload 1 of 2, '(props: { compone ...

Creating a vertical bar chart in D3 with a JSON data source embedded within the code

Struggling to generate a stacked bar graph in D3.js. The axes are displaying correctly, but the data on the graph is not showing up. Any suggestions on what could be causing this issue? JS: var svg = d3.select("#recovery__table"), margin = {top: 20, ...

Converting SVG string to PNG output in Node.js with GraphicsMagick (gm

I'm looking to convert an SVG string into a PNG and display it on the browser. I've reviewed a few resources: Currently, I can successfully output a png but not an svg. Writing the svg to a file works fine, it's just the streaming part that ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

Transferring an array value through ajax within a Wordpress environment

I recently executed an ajax call using jQuery.ajax and implemented it as follows: jQuery.ajax({ url: wpgiftstoreAjax.ajaxurl, type: 'POST', dataType: 'JSON', data: { ...

Issue with displaying Youtube search API results on EJS template file

I'm currently trying to integrate the YouTube Search API into my website. However, when I make the API call from my route, the results are returned but the page is rendered before the results finish processing - likely due to the asynchronous behavior ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

Converting a string to a JSON array with Jackson in RESTful APIs

As I delve into the world of JSON and REST, I find myself testing a REST API that returns strings in the following format: [{ "Supervisor_UniqueName": "adavis", "Active": "true", "DefaultCurrency_UniqueName": "USD", "arches_type": "x-zensa ...