• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar

CodingStatus

- Free Source Code for Web Applications

  • HTML
  • JavaScript
  • jQuery
  • ReactJS
  • Ajax
  • Node.js
  • PHP
  • SQL
  • Interview Questions
  • Installation

Load Records on Select Box using Ajax, PHP & MySQL

April 16, 2022 By Md Nurullah

In this tutorial, You will learn to load records on a select box using ajax, PHP & MySQL with some simple steps. These steps are very easy to understand and implement in web applications.

Let’s know how to work it, When you select an option of the dropdown then data will be displayed in a table without reloading the web page.

Here, I have displayed some students’ records in an HTML table based on their courses. Once you learn it, you will easily customize it according to your project requirement.

ajax load records on select box

Display Data From Database Based on Dropdown Selection using Ajax in PHP

 

Before getting started its coding, you should create the following folder structure –

codingstatus/
     |__ database.php
     |__ ajax-script.php
     |__ display-data.php
     |__ display-script.php

1. Create a Database & Table

First of all, Create a MySQL database with the name ‘codingstatus’

Database Name – codingstatus

CREATE DATABSE codingstatus;

Create a table with the name of ‘course’ to insert the course name

Table Name – courses

CREATE TABLE `courses` (
`id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`courseName` varchar(255) DEFAULT NULL
);

Also, create another table with the name of ‘students’

Table Name – students

CREATE TABLE `students` (
`id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`fullName` varchar(255) DEFAULT NULL,
`courseName` varchar(255) DEFAULT NULL,
);

2. Connect PHP to  Database

Now, Connect the database to display data based on dropdown selection

File Name – database.php

<?php

$hostName = "localhost";
$userName = "root";
$password = "";
$databaseName = "codingstatus";

 $conn = new mysqli($hostName, $userName, $password, $databaseName);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

?>

3. Insert Data into a Table

After creating the database & table, you have to insert data into both tables. If you don’t know, you can do it with the help of the following article –

Insert Select Option Value with another input value using PHP & MySQL

4. Create a Select Box

To display data from the “courses” table in the database, you have to follow the following steps –

Step -1: Include the database.php file

Step-2: Create a select option input field with the name=”courseName” and onclick=”loadData()”. Where loadData() is explained in the next step.

Step-3: Also, create a submit input field with the name=”submit”

Step-4:  Fetch  ‘courseName’ from ‘courses and display it in the select option

Step-5:  Create a div with id=”displayData”

Step-6: Include jQuery CDN

File Name – display-data.php

<?php
include("database.php");

?>
<form action="" method="post">
<select id="courseName" onchange="loadData()">
    <option value="">Select Course</option>
    <?php 
    $query ="SELECT id, courseName FROM courses";
    $result = $conn->query($query);
    if($result->num_rows> 0){
        while($optionData=$result->fetch_assoc()){
        $option =$optionData['courseName'];
        $id =$optionData['id'];
    ?>
    <option value="<?php echo $id; ?>" ><?php echo $option; ?> </option>
   <?php

    }}
    ?>
</select>

</form>
<!-----display data-->

   <div id="displayData">
   </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script type="text/javascript" src="ajax-script.js"></script>



5. Load Records on Select Box

In this step, you have to write jquery ajax code to load records while you change the dropdown option.

Step-1: Create a custom function loadData() and implement the next steps within it.

Step-2: get option id using $(“#courseName”).val() and store it in a variable id

Step-3: declare the following points within the $.ajx({})

  • type: post
  • url : display-script.php – this file is explained in the next step.
  • data: {courseId: id}
  • success: function(){}

File Name – ajax-script.php

var loadData = function(){

   const id = $("#courseName").val();
  
    $.ajax({    
        type: "post",
        url: "display-script.php", 
        data:{courseId:id},      
        dataType: "html",                  
        success: function(data){   
         
           $("#displayData").html(data);
        }
    });
};

 

6. Fetch Records From the Database

To display data in an HTML table, you will have to follow these steps –

Step-1: Include the ‘database.php’

Step-2: Create an HTML table with the three columns like s.n, full name, & course name

Step-3: display data in HTML table using foreach loop

File Name – display-script.php

<?php
include("database.php");

/// edit data
if(isset($_POST['courseId'])){
    $courseId= $_POST['courseId'];
   
   $fetchData =fetchDataById($courseId);
   displayData($fetchData );

}

function fetchDataById($courseId){
    
    global $conn;
  $query ="SELECT fullName, emailAddress FROM students WHERE courseId='$courseId'";
    $result = $conn->query($query);
    if($result->num_rows> 0){
      $students= mysqli_fetch_all($result, MYSQLI_ASSOC);
    }else{
     $students=[];
    }
    return $students;
}
function displayData($fetchData){
 echo '<table border="1" cellspacing="0" cellpadding="5">
        <tr>
            <th>S.N</th>
            <th>Full Name</th>
            <th>Email Address</th>
           
        </tr>';
 if(count($fetchData)>0){
      $sn=1;
      foreach($fetchData as $data){ 
  echo "<tr>
          <td>".$sn."</td>
          <td>".$data['fullName']."</td>
          <td>".$data['emailAddress']."</td>
         
   </tr>";
       
  $sn++; 
     }
}else{
     
  echo "<tr>
        <td colspan='7'>No Data Found</td>
       </tr>"; 
}
  echo "</table>";
}
?>

 

 

Filed Under: Ajax

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Primary Sidebar

Latest Tutorials

  • How to Install Express Application Using Express Generator Tool
  • Registration Form using Ajax, PHP & MySQL
  • Filter Data with Checkboxes in PHP & MySQL
  • Filter Data by Category in PHP & MySQL
  • Filter Prices From Low to High in PHP, MySQL

Popular Tutorials

  • Registration Form using Ajax, PHP & MySQL
  • Ajax File Upload – Without Refreshing Page
  • Load More Data on Infinite Scroll Using Ajax & PHP
  • How to Fetch Data From Database Using Ajax
  • How to Update Data Using Ajax in PHP

Categories

  • Ajax (11)
  • Django (5)
  • HTML (4)
  • Installation (3)
  • Interview Questions (5)
  • JavaScript (20)
  • jQuery (11)
  • Laravel (2)
  • Node.js (23)
  • PHP (42)
  • ReactJS (35)
  • SQL (12)
  • Tips (7)
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved