I am using Rails and I am building a page that creates new "people"(people/new). Using javascript, I scan a page with user inputs and i end up with a javascript object looking like this:
obj = { name: "John", age: 30, city: "New York" };
I want to add an event listener (keypress q) that saves this hash into the database, which looks like this:
create_table "people", force: :cascade do |t|
t.string "name"
t.integer "age"
t.string "city"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Even though i have inputs that i scan, there IS NO form.
I know how to JSON.stringify and I know how eventListeners work but I am unsure how I can send that stringified object from javascript to ruby code that saves it to the database.
Here is the Javascript i have done so far : app/assets/javascript/testing.js
addEventListener('keyup', event => {
if (event.key === "q") {
var array = []
var inputs = document.querySelectorAll("input")
inputs.forEach ((input) => {
array.push(input.value)
})
var name = array[0]
var age = array[1]
var city = array[2]
var hash = {}
hash["name"]= name
hash["age"]= age
hash["city"]= city
var stringified = JSON.stringify(hash)
}
} )
And here is what my controller looks like :
class PeopleController < ApplicationController
def index
@people = Person.all
end
def new
@person = Person.new
end
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age, :city)
end
end
What I expect is that when the "q" key is pressed, whatever is present in the inputs is saved to the database