Utilizing AJAX POST requests from JavaScript to a Rails 4 controller while implementing Strong Parameters

As a newcomer to Rails, I am looking to insert song_id and title received from JavaScript via AJAX POST into a MySQL database.


In my JavaScript file:

var song_id = "23f4";
var title = "test";

$( document ).ready( function() {
  jQuery.ajax({
        url: 'create',
        data: "song_id=" + song_id + "&title=" + title,
        type: "POST",
        success: function(data) {
          alert("Successful");
        },
        failure: function() {
          alert("Unsuccessful");
        }
      }); 
  } );


In my editor_controller.rb:

class EditorController < ApplicationController

  def new
    @song = Song.new
  end

  def create
    logger.debug("#{params[:song_id]}")
    logger.debug("#{params[:title]}")
    @song = Song.new(song_params)

    if @song.save
      redirect_to root_path
    else
      flash[:notice_song_failed] = true
      redirect_to root_path
    end 
  end

  private   
  def song_params
    params.require(:song).permit(:song_id, :title)
  end


When running the Rails app with this code, the Console informs me of an issue:

ActionController::ParameterMissing at /editor/create

param is missing or the value is empty: song


I tried using:

private 
def song_params
  params.require(:song).permit(params[:song_id], params[:title])
end

but it produces the same error. Additionally, the terminal log shows:

Started POST "/editor/create" for ::1 at 2015-04-01 01:07:23 +0700

Processing by EditorController#create as /

Parameters: {"song_id"=>"23f4", "title"=>"test"}

23f4

test

Completed 400 Bad Request in 1ms


Is there something missing in my code? Thank you in advance.

+

Answer №1

No song parameter is being sent in your request. To fix this, make sure to add the song parameter in the data line of your jQuery.ajax call:

data: {song: {song_id: song_id, title: title}}

Answer №2

The following code snippet:

params.require(:song).permit(params[:song_id], params[:title])

is essentially instructing the system to demand the presence of the 'song' parameter, and to only allow access to 'song_id' and 'title'. If the song parameter is missing, a bad request error will be triggered.

You have two options:

  1. Modify the code by eliminating the requirement for 'song'

or

  1. As suggested by @infused, adjust your ajax call to transmit a song JSON object instead.

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

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

An error occurred - 0x800a1391 - JavaScript runtime error: The function 'SelectAllCheckBoxes' has not been defined

I'm currently in the process of learning web development and I am trying to incorporate jQuery into my ASP .NET page. Within the header section, I have included the necessary references: <head id="Head1" runat="server"> <link href=" ...

What is the best way to retrieve information from a JavaScript file?

Learning.vue <template> <div> <button @click="test()">test</button> </div> </template> <script> import records from './records.js' export default { data () { return { ...

Struggling with sluggish performance during a loop while updating a MYSQL table

My current code is experiencing significant performance issues while using a WHILE LOOP to update table stock_figures with data from table product in the same database. The code iterates through each row in product, extracting the product_id and wholesale_ ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

Receiving an 'undefined' result in an asynchronous response even with 'await' and 'then' statements implemented

I'm struggling with sending a GET request, parsing the response, and passing it to another function. It seems like I'm having difficulty dealing with the asynchronous nature of the response. I prefer to stick to using Node.js' built-in modu ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

The XMLHttpRequest header is not being sent by jQuery.ajax

Looking at version 1.7.2, I am currently in the process of submitting a form using jQuery.ajax(): jQuery.ajax({ url: form.attr('action'), method: 'POST', dataType: 'json', data: {post_id: id}, success: fun ...

send the value from the input field to the designated button - link the two buttons

My goal is to create a feature where users can click on a button within the map and open an external page in Google Maps with specific dimensions (500 X 600) and without the Menu bar, Tool bar, or Status bar. // Custom Button Functionality by salahineo ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...

Can a page be replaced by another include?

THE ISSUE I am facing a problem where I am unable to override the current page using include. if ($LS::getUser('clan') || isset($_GET['clan']) && !isset($_GET['search'])) { include("res/templates/clan-overview.ph ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

What is the best way to retrieve the Firebase API key from an Express backend in order to initialize firebase.initializeApp()?

At the moment, my Firebase.js file is structured to fetch the API key from the .env file on the client side. Here's a snippet of the code: import firebase from "firebase/compat/app"; import "firebase/compat/auth"; import "firebase/compat/firestore" ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

Bringing in JavaScript files from a Bootstrap theme to incorporate them into a Vue3 application

Incorporating Bootstrap 5, a HTML theme with a CSS bundle file, and separate JS bundle files (main JS bundle file and plugin bundle file) containing Bootstrap code base + custom template features into a Vue 3 project is my current objective. I aim to utili ...

Issue with Caching during Javascript Minification

I Have ASP.Net MVC 3 App. Utilizing YUICompressor.Net for compressing Javascript and CSS files post build with MSBuild. The minimized javascript file is named JSMin.js and the CSS file is CssMin.css. In my master page, I reference these files as shown bel ...