Encountered an AJAX error 400 indicating a bad request - the challenge lies in passing parameters from one method to the create method within the same controller

Two models exist in my application: User and Record. The scaffold option was used to generate both models. I am currently working within the partial _form.html.erb of my User model, where I have written some JavaScript to store information in a variable named value.

An AJAX call was implemented to send this JavaScript variable to my User Controller. Below is the JavaScript code:

var value = $('input#quantity').val();

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

});

In the route configuration file, the routes were set as follows:

resources :user
resrouces :record

post '/info'=>'users#registration'

The User controller contains the following methods:

def registration
    @value = params[:value]
    
    render json: 'ok'
  end

  def create
    @user = User.new(user_params)
    
    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(user: @user, value: @value)
         
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
      format.js
    end
  end

I aim to create a new Record when creating a new User. This Record should have the ID of the created User and the attribute value equal to @value.

Although I know that Record.create(user: @user) creates a new Record with the User's ID, my question is how to pass @value from the registration method and make it accessible in the create method?

I have considered using after_create methods for models, but I prefer not to. It is crucial for me to have the @value variable available in the create method without these methods.

When attempting to route my AJAX call to the create method, I encountered an error 400: bad request.

Answer №1

400 Bad Request error indicates that the server cannot recognize the data stream sent by the client. To resolve this issue, consider including dataType:"json" in your AJAX post request. Additionally, you may find this answer on 400 Bad request helpful in understanding and fixing the error.

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

How can you display an alert message when new data is successfully added to a database using ajax?

In my web application, I have implemented a functionality to display an alert message when new data is successfully inserted into the database. The Ajax code below is responsible for sending a request to the EditDeleteLecture.php file. However, a challenge ...

Instructions on exporting binary data to a PNG file using nodejs

How can I convert a binary nodejs Buffer object containing bitmap information into an image and save it to a file? Edit: I attempted using the filesystem package as suggested by @herchu, but when I tried the following code: let robot = require("robotjs" ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

Selenium allows the liberation of a webpage from suspension

I'm facing an issue with resolving the suspension of a website as shown in the image below. My goal is to access a ticket selling website every 0.1 seconds, but if it's busy, I want it to wait for 10 seconds before trying again. Visit http://bu ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

Error message: The HttpPostedFileBase object is null when processing a controller or AJAX request

I'm having trouble uploading a file and sending it to the controller, as it keeps returning null. Below is the code snippet: [HttpPost, ValidateAntiForgeryToken] public JsonResult Edita(string nome, string login, string email, string dataNa ...

Customize your Vue 3 application with custom Axios functions for handling GET, PUT,

I am looking to enhance my use of axios by customizing the get, post, and put functions. After performing the axios.create() operation, I want every subsequent get operation to include a then and catch block. import axios from "axios"; export de ...

Is there a way to automate testing my HTML code in sections?

I am facing the challenge of testing a lengthy HTML file filled with various functionalities for showing and hiding elements. For instance, users can choose to hide the logo, display a large title, show specific blocks, and more. These options can be combi ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

Stop auto-refreshing when a popup is active

As I work on a GSP (Grails) page, there are links that trigger a popup using thickbox (JQuery). Recently, I implemented a simple JavaScript to refresh the page every 5 minutes. However, I encountered an issue whereby the popup closes whenever the page is ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Viewing documents stored on the file server using the frontend interface (angular)

I am currently working on an Angular application that interacts with a .NET Core API. I have encountered an issue where the file upload process successfully uploads files to a file server, but I am unable to access these files on the front end. Despite at ...

Looking for guidance on how to fill the "via" table in Sequelize?

I'm currently trying to understand the N:M relationship in sequelize, specifically regarding populating the "through" table. Here are the models I am working with: Product / Category 'use strict'; module.exports = (sequelize, DataTypes) = ...

AngularJS view is not refreshing

I am facing an issue with updating a view via a controller that fetches data from a service. Despite changing the data in the service, the view does not reflect these updates. I have created a simplified example from my application, which can be found here ...

ionRangeSlider adjusts values according to a given percentage

I am currently utilizing the ionRangeSlider library for my project. My goal is to synchronize 2 sliders based on their current percentage. Below is the code I have implemented: $(function(){ $("#foo").ionRangeSlider({ type: "single", grid: t ...

Is it possible to modify a particular entry in Ember Data without initiating any HTTP requests?

Within my Ember.js application, I have a model named emails structured as follows: import DS from 'ember-data'; export default DS.Model.extend({ label : DS.attr('string'), primary : DS.attr('string'), email : ...

Searching for a nested object in Javascript using regular expressions

Presenting my data structure: var foo = { "Category1": [ {"Company1": {"URL": ["DomainName1", "DomainName2"]}}, ... ], ... } Typically, I access DomainName1 like this: foo["Category1"][0][" ...

Error: Jquery unrecognized - syntax issue

How can I properly add or remove the active class from an element based on a data-filter attribute in jQuery? When I attempt to do this, I receive the following error message:Uncaught Error: Syntax error, unrecognized expression: li[data-filter=.arroz-1] $ ...

Autocompleter Component: Blur input when clicking on content

Currently, I am facing an issue while using MUI's Autocomplete on mobile. The problem arises when the dropdown list is open and I attempt to interact with an element within that list, such as a button. Upon clicking on this interaction element, the in ...

collection of items with varying dates

I have an array of objects, each containing a date. My goal is to create a new array of objects grouped by weeks. Here is an example code snippet: const data = [ { "id": 1, "status": 1, "createdAt": "2022-05-01T08:28:36.284Z" }, { "id ...