I'm practicing making a web app in Sinatra and I'm trying update a page so that information from a database is displayed once a button is clicked (more specifically, I'm a using a student database with the students age, name, and campus location). I have a route with 5 buttons (one for each campus) and once a campus button is clicked, I want the page to update with all the students information (from that campus) on the same page.
This is what I have for the app.rb
require 'sinatra'
require 'sqlite3'
set :public_folder, File.dirname(__FILE__) + '/static'
db = SQLite3::Database.new("students.db")
db.results_as_hash = true
get '/' do
@students = db.execute("SELECT * FROM students")
erb :home
end
get '/students/new' do
erb :new_student
end
get '/students/campus' do
erb :campus
end
get '/students/campus/:campus' do
erb :campus
campus_data = db.execute("SELECT * FROM students WHERE campus=?", params[:campus])
campus_data.to_s
response = ""
campus_data.each do |student|
response << "ID: #{student['id']}<br>"
response << "Name: #{student['name']}<br>"
response << "Age: #{student['age']}<br>"
response << "Campus: #{student['campus']}<br><br>"
end
response
end
post '/students' do
db.execute("INSERT INTO students (name, campus, age) VALUES (?,?,?)", [params['name'], params['campus'], params['age'].to_i])
redirect '/'
end
This is what I have for the campus.erb
<!DOCTYPE html>
<html>
<head>
<title>Campus Cohorts</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Cohorts</h1>
<p>Click on a button to see all students from that location.</p>
<a href="/students/campus/SF"><button type="button">San Francisco</button></a>
<a href="/students/campus/NYC"><button type="button">New York City</button></a>
<a href="/students/campus/SD"><button type="button">San Diego</button></a>
<a href="/students/campus/CHI"><button type="button">Chicago</button></a>
<a href="/students/campus/SEA"><button type="button">Seattle</button></a>
</body>
</html>
At the moment, if a button is clicked it will redirect you to a new page with the students information form that campus, how I can render the information on the same page?