Tips for successfully passing a JavaScript variable and storing it in a Rails database

I'm a beginner in Rails and I'm attempting to store a javascript variable from the view to the Rails Controller, which is then saved to a Model (database). The user participates in a quiz or survey and is then redirected to a results page. On this results page, there is JavaScript code that calculates the marks/results, and my goal is to save these marks to a database.

After some research, I found that the most effective solution is to utilize AJAX on the front-end to send the data to the controller on the back-end for processing.

I have a single controller named 'quiz' where I've implemented all the necessary methods, and a corresponding model called 'Score' to store the results. The user's result should be saved once they reach the result page.

This is what I have done so far:

In quiz_controller.rb

def result
    @title = "Quiz Results"
end

def score
    @mark = Score.all
end

def mark
    quiz_name = params[:quiz]
    mark = params[:mark]
    @mark = Score.new(score_params)
    @mark.save
end

private 
    def score_params
        params.require(:score).permit(:quiz, :score)
    end

In result.html.erb

<script>

var mark = calcMark();

$.ajax({
  url: "http://localhost:3000/mark?quiz=" + quiz + "&mark=" + mark,
  type: "POST",
  success: function (data) {
    console.log(data);
  }
});
</script>

In 2019******_create_scores.rb

t.string "quiz", :limit => 50, :null => false
t.column "score", :decimal, :limit => 30, :null => false
t.datetime "created_at"
t.datetime "updated_at"

In routes.rb

get 'result' => 'quizs#result'
post 'result/mark' => 'quizs#mark'

If you have any suggestions on how to improve my implementation or if you notice any issues with my route configuration or AJAX URL, please let me know. Thank you in advance!

Answer №1

Here is the recommended ajax script for your quiz:

$.ajax({
    url: "/result/mark",
    data: {"quiz": quiz, "score": mark},
    type: "POST",
    success: function (data) {
        console.log(data);
    }
});

This is the Rails action code snippet:

def mark
    @mark = Score.create!(score_params)
end

private 
    def score_params
        params.permit(:quiz, :score)
    end

Answer №2

If you want to send post data, the key step is to define a data object for $.ajax

$.ajax({
    url: "/result/submit",
    data: {"form": form, "data": data},
    type: "POST",
    success: function (response) {
        console.log(response);
    }
});

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

Insert clickable links into columns within DataTables

New to using DataTables, I have a webpage that utilizes client-side processing for loading data. I am trying to insert hyperlinks in my columns using "columns.render" to display details from the entire row when the ID/pk value matches the linked text. This ...

Tips for reaching a node.js application deployed on Heroku

Trying to deploy my node.js app to Heroku has been a challenge. Despite watching various tutorials and reading the documentation, I'm stuck on how to send and receive data from the hosted node.js app. The communication between my webpage and the node. ...

What other strategies can I utilize to enhance my bundle and boost webpage loading time?

In my React application, I've utilized various libraries like redux, redux-form, react-router, leaflet, react-bootstrap, redux-thunk, and more. The minified bundle size is 531kb, while the vendor file stands at 5.32mb. For bundling and optimization, ...

Unable to pass the new value to the onclick function

I am currently working with Gridster.js in combination with Twitter Bootstrap. My goal is to have a modal pop up when I double-click on a grid, allowing for customization of the grid. Currently, I am focusing only on the delete option. The issue I am fac ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can so ...

Can someone explain how to implement an onclick event for a div element inside an iframe using jquery or javascript?

Understanding the HTML Structure <iframe src="#" scrolling="no" id="gallery-frame"> <div class="gv_filmstrip"> <div class="gv_frame"> <div class="gv_thumbnail current"> <img src="images/grandstand-padang-right/1.jpg"> </d ...

Trouble with Ajax.net update panels persisting on Mozilla Firefox

There seems to be an issue with the postback functionality for updating the ajax updatePanel. While it works perfectly in IE, Mozilla is causing the entire page to reload instead of just the panel. <asp:ScriptManager ID="ScriptManager1" runat="server"& ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

Monitor user inactivity with JavaScript

Our website contains iframe links to various content sites where users can take online exams. Some of these exams on the content pages run for over 3 hours. Additionally, an exam guard feature is implemented to prevent users from engaging in other activiti ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

The function db.query in Node.js isn't working as expected

Currently working with Node.js and Express, I am seeking to run queries on a MySQL database hosted on AWS EC2. In my db_connection.js file, I have established a connection to the database and attempted to export the connection (db) for use in other JavaSc ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

Incorporating Redis within an Express route

My goal is to store a value in a specific key in one route: /api/foo?redisKey="1" (setting value for the key id=1) Then, in another route, I want to retrieve the value: /api/bar?redisKey="1" (getting value for key id=1) Since redis operates asynchronou ...

Inserting items into arrays in Angular

I've encountered an issue with pushing an object into an array. The array contains objects, and this component is responsible for displaying them: <div class="row" *ngFor="let element of dietList"> {{element.name}} {{ element.weight }} </d ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

Are there any specific plugins or recommended methods for Gatsby to generate each build in a different language?

If I have a website built in Gatsby with English content on www.someWebsiteUrl.com, how can I create the same page with Spanish content on www.someWebsiteUrl.es? Is there a way to specify which site with specific translations should be generated? For exam ...

Generate an inclusive list featuring li elements with intricately detailed content within each

Currently, I am in the process of developing a web component and here is my code snippet: <ul class="list-with-arrow${this.inverse ? '--inverse' : ''}"> ${this.listData.map((item, index) => { ...