
Home in PostgreSql
Working with Dependent Dropdowns in Go Fiber Using PostgreSQL
To implement a dependent dropdown in Go Fiber with PostgreSQL, you need:
- Go Fiber backend to fetch and serve data
- Frontend (HTML + jQuery/AJAX) to update dropdowns dynamically
1. PostgreSQL Database Structure
Example: Suppose we have a countries table and a states table where each state is linked to a country.
INSERT INTO countries (name) VALUES ('USA'), ('India');INSERT INTO states (country_id, name)
VALUES(1, 'California'),(1, 'Texas'),(2, 'Maharashtra'),(2, 'Karnataka');
2. Go Fiber Backend
Install required packages
go get github.com/gofiber/fiber/v2go get github.com/jmoiron/sqlxgo get github.com/lib/pq
Database Connection
package mainimport ("database/sql""fmt""log""github.com/gofiber/fiber/v2"_ "github.com/lib/pq")
var db *sql.DBfunc connectDB() {func getCountries(c *fiber.Ctx)
var name stringrows.Scan(&id, &name)countries = append(countries, map[string]interface{}
{"id": id,"name": name,})}return c.JSON(countries)}
Fetching States Based on Country Selection
func getStates(c *fiber.Ctx) var name stringrows.Scan(&id, &name)
states = append(states, map[string]interface{}{"id": id,"name": name,})}return c.JSON(states)}
Setup Fiber Routes
func main() {connectDB()app := fiber.New()app.Get("/countries", getCountries)
app.Get("/states", getStates)log.Fatal(app.Listen(":3000"))}
3. Frontend (HTML + jQuery)
html><html lang="en"><head> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dependent Dropdowntitle>
<script src="https://code.jquery.com/jquery-3.6.0.min.js">script>head><body>
<label for="country">Select Country:label> <select id="country">
<option value="">Select a countryoption> select>
<label for="state">Select State:label> <select id="state">
<option value="">Select a stateoption> select> <script>
$(document).ready(function(){ // Load countries
$.get("/countries", function(data){
data.forEach(function(country){
$("#country").append(`">${country.name}`); }); });
// Load states based on selected country
$("#country").change(function(){
var countryID = $(this).val(); $("#state").html(''); if(countryID){
$.get("/states?country_id=" + countryID, function(data){
data.forEach(function(state){
$("#state").append(`">${state.name}`); });
}); } }); });
script>body>html>
Summary
✅ PostgreSQL Tables: countries
and states
✅ Go Fiber API Endpoints: /countries
and /states?country_id=ID
✅ Frontend: jQuery AJAX to dynamically fetch states