How to populate a dropdown with students using AJAX , PHP and show the selected student's details on change.

Table Structure & Sample Data

 
CREATE TABLE students (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  address TEXT NOT NULL
);
 
INSERT INTO students (name, email, phone, address)
VALUES ('John Doe', 'john.doe@example.com', '+1234567890', '123 Main Street'), ('Jane Doe', 'jane.doe@example.com', '+9876543210', '456 Elm Street'),('Michael Smith', 'michael.smith@example.com', '+0987654321', '789 Maple Street');
 
 

PHP Code

Structure:

  • index.php: Displays the dropdown and detail container.
  • getStudents.php: Fetches student names for the dropdown.
  • getStudentDetails.php: Fetches details for the selected student.
  • db.php : For database connection

 

Create a file named index.php for the main page , another file named getStudentDetails.php   and another file named getStudents.php for handling AJAX requests.

Create another file named db.php to connect to the database

// index.php
 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Details with AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Student Details</h1>
<label for="student_id">Select Student:</label>
<select name="student_id" id="student_id"></select>
<br>
<div id="student_details"></div>
 
<script>
        $(document).ready(function() {
            // Function to populate student dropdown with AJAX
            function populateStudents() {
                $.ajax({
                    url: "getStudents.php",
                    method: "GET",
                    dataType: "json",
                    success: function(data) {
                        $("#student_id").empty();
                        $("#student_id").append("<option value=''>Select a student</option>");
                        for (var i = 0; i < data.length; i++) {
                            var student = data[i];
                            $("#student_id").append("<option value='" + student.id + "'>" + student.name + "</option>");
                        }
                    }
                });
            }
 
            // Populate student dropdown on page load
            populateStudents();
 
            // Show student details when student is selected
            $("#student_id").change(function() {
                var student_id = $(this).val();
                if (student_id) {
                    $.ajax({
                        url: "getStudentDetails.php",
                        method: "GET",
                        dataType: "json",
                        data: { student_id: student_id },
                        success: function(data) {
                            console.log(data);
                            $("#student_details").empty();
                            $("#student_details").append("<h3>" + data.name + "</h3>");
                            $("#student_details").append("<p>Email: " + data.email + "</p>");
                            $("#student_details").append("<p>Phone: " + data.phone + "</p>");
                            $("#student_details").append("<p>Address: " + data.address + "</p>");
                        }
                    });
                } else {
                    $("#student_details").empty();
                }
            });
        });
    </script>
</body>
</html>
 

getStudents.php

 
//getStudents.php
 
require_once "db.php";
 
// Fetch student names and IDs
$stmt = $pdo->prepare("SELECT id, name FROM students");
$stmt->execute();
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
// Return JSON response
header('Content-Type: application/json');
echo json_encode($students);
?>
 

getStudentDetails.php

 
// Database connection 
require_once "db.php";
 
if (isset($_GET['student_id'])) {
    $studentId = $_GET['student_id'];
    
    // Fetch student details
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = :id");
    $stmt->bindParam(':id', $studentId, PDO::PARAM_INT);
    $stmt->execute();
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($student);
} else {
    echo json_encode([
        'error' => 'Student ID not provided'
    ]);
}
 

Explanation:

  1. index.php:

    • Imports jQuery.
    • Displays the dropdown with ID "student_id" and a container for details with ID "student_details".
    • Uses jQuery AJAX to:
      • Populate the dropdown with student names from "getStudents.php".
      • Fetch and display details for the selected student from "getStudentDetails.php" using the student ID.
  2. getStudents.php:

    • Connects to the database using PDO.
    • Fetches student names and ID from the "students" table.
    • Loops through each student and generates an HTML option element with ID and name.
    • Returns the generated HTML options to "index.php" to populate the dropdown.
  3. getStudentDetails.php:

    • Connects to the database using PDO.
  4. db.php
  • Database credentials.

 
//db.php
 
 
// Database connection
$host = "localhost";
$db = "your_database_name";
$username = "your_database_username";
$password = "your password";
 
try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}