


Dynamically loading drop-down menu: JavaScript gets selected value and interacts with PHP backend
Oct 15, 2025 pm 09:24 PMThis tutorial explains in detail how to use JavaScript to obtain the selected value of an HTML drop-down menu, and use AJAX technology to send the value to the PHP backend. The PHP script executes a database query based on the received value and returns the results to the front end, ultimately achieving dynamic updating of the second drop-down menu to build an interactive web form.
In web development, it is often necessary to dynamically update page content based on user selections. One of the most common scenarios is the linkage drop-down menu. For example, when the user selects an option in one drop-down menu, another drop-down menu will load the corresponding sub-options based on the former selection. This tutorial will delve into how to use JavaScript to obtain the selected value of the drop-down menu, pass it to the PHP backend for processing through AJAX technology, and finally achieve dynamic data loading.
Part 1: Get the selected value of the drop-down menu in JavaScript
First, we need to make sure that we can correctly retrieve the user's selection in the first drop-down menu via JavaScript on the client side (browser).
Original problem analysis: In the provided code snippet, the attempt to get the selected value is:
document.getElementById('lblmess').innerHTML = (formid.listid[formid.listid.selectedIndex].value) $element = document.getElementById("lblmess"); console.log($element.innerHTML)
There are several problems with this code:
- Although it is feasible to access form elements directly through formid.listid[formid.listid.selectedIndex].value, a more concise and recommended way is to use the onchange event to pass the value of the current element.
- Assigning a value to lblmess's innerHTML and then reading it from lblmess adds an unnecessary intermediate step.
- The most critical thing is that $element is a JavaScript variable, which cannot be used directly in PHP code, because PHP is executed on the server side, while JavaScript is executed on the client side. The two operating environments are different and variables cannot be shared directly.
Optimized JavaScript value acquisition method: A more concise, efficient and recommended approach is to directly pass the value of the currently selected item as a parameter to the JavaScript function in the onchange event.
HTML structure modification: change onchange="getdll()" to onchange="getdll(this.value)". this.value represents the value of the
JavaScript function modification: The getdll function can now directly receive the selected value.
<script> function getdll(selectedValue) { // At this time, selectedValue is the value selected in the first drop-down menu console.log("The selected value is: " selectedValue); // The value can be displayed in lblmess for debugging or user feedback document.getElementById('lblmess').innerHTML = "You selected: " selectedValue; // Next, we will use AJAX to send this value to the server // ... (AJAX code will be detailed in the next section) } </script>
Part 2: Understanding the nature of client-server interaction
Before diving into AJAX, it's crucial to understand the fundamental differences between client-side (JavaScript in the browser) and server-side (PHP).
- Client (JavaScript) : Executed in the user's browser and responsible for handling the user interface, user interaction and front-end logic. It has no direct access to the server's file system or database.
- Server side (PHP) : Executed on the Web server, responsible for handling data storage, database operations, business logic and generating dynamic web content. PHP is executed once when the page is loaded, and HTML is generated and sent to the browser.
Therefore, JavaScript variables cannot be used directly in PHP code and vice versa. To achieve data exchange between the two, HTTP requests are required. AJAX (Asynchronous JavaScript and XML) is the key technology to achieve this kind of asynchronous communication.
Part 3: Using AJAX to implement dynamic data loading
AJAX allows JavaScript to send HTTP requests to the server and receive responses without reloading the entire page. This allows us to send the selected value of the first drop-down menu to the PHP script. After the PHP script queries the database, it returns the results to JavaScript, which then uses the data to dynamically update the second drop-down menu.
Overview of how AJAX works:
- Event triggering: The user makes a selection in the first drop-down menu, triggering the getdll(selectedValue) function.
- Send a request: The getdll function uses the fetch API (or XMLHttpRequest) to send an asynchronous HTTP request to a PHP script on the server, passing the selectedValue as a parameter.
- Server processing: The PHP script receives the request and selectedValue. It executes database queries using this value as a condition.
- Send response: The PHP script sends the query results (usually in JSON format) back to the client as an HTTP response.
- Client processing: The getdll function receives the response from PHP. It parses the JSON data and then iterates through the data, dynamically creating and populating the
Front-end JavaScript (using the fetch API): We will modify the getdll function so that it sends an AJAX request.
<script> function getdll(selectedValue) { document.getElementById('lblmess').innerHTML = "You selected: " selectedValue; const roomListSelect = document.getElementById('roomList'); // Clear the existing options of the second drop-down menu roomListSelect.innerHTML = '<option value="">Loading...'; // Temporarily display the loading status // Check whether the selectedValue is valid, for example, not "0" if (selectedValue === "0") { roomListSelect.innerHTML = '<option value="">Please select a valid office room'; return; //Do not send request} // Use the fetch API to send a POST request to the PHP script fetch('get_rooms.php', { method: 'POST', // or 'GET', depending on how your backend receives parameters headers: { 'Content-Type': 'application/x-www-form-urlencoded', // Commonly used Content-Type }, body: 'o_id=' selectedValue // Send the selected value as a POST parameter}) .then(response => { if (!response.ok) { throw new Error('Network response is abnormal'); } return response.json(); // Parse JSON response}) .then(data => { // Clear all old options roomListSelect.innerHTML = ''; if (data. length > 0) { // Loop through the received data and create a new <option> for each data item data.forEach(room => { const option = document.createElement('option'); option.value = room.id; // Assume the data contains the id and room_name fields option.textContent = room.room_name; roomListSelect.appendChild(option); }); } else { roomListSelect.innerHTML = '<option value="">No meeting room available'; } }) .catch(error => { console.error('An error occurred while obtaining conference room data:', error); roomListSelect.innerHTML = '<option value="">Loading failed, please try again'; }); } </script>
Backend PHP script (handling AJAX requests): Create a new file called get_rooms.php to handle AJAX requests sent by the front end.
<?php // get_rooms.php //Introduce the database connection file // Assume that the $conn variable has been connected to the database through include "db_conn.php"; etc. // Example: $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Replace with your database name $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //Set the response header to JSON header('Content-Type: application/json'); // Get the o_id parameter in the POST request $o_id = isset($_POST['o_id']) ? $_POST['o_id'] : ''; $rooms = []; // Array used to store query results if (!empty($o_id) && is_numeric($o_id)) { // Use prepared statements to prevent SQL injection $stmt = $conn->prepare("SELECT id, room_name FROM `assembly_hall` WHERE o_id = ? ORDER BY `room_name` ASC"); $stmt->bind_param("i", $o_id); // "i" represents integer type $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $rooms[] = $row; } } $stmt->close(); } // Encode the result into JSON and output echo json_encode($rooms); $conn->close(); ?>
Part 4: Complete sample code
Integrate the above HTML, JavaScript and PHP together to form a complete example of a linked drop-down menu.
index.php (main page file):
<?php // Assume that the database connection $conn has been established here // Sample connection code (please modify according to your actual situation) $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Replace with your database name $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic linkage drop-down menu</title> <style> .custom-select { padding: 8px; border: 1px solid #ccc; border-radius: 4px; margin-bottom: 10px; } #lblmes { margin-top: 10px; font-weight: bold; color: #333; } </style> <h1>Select office and conference room</h1><script> function getdll(selectedValue) { document.getElementById('lblmess').innerHTML = "You selected the office ID: " selectedValue; const roomListSelect = document.getElementById('roomList'); // Clear the existing options of the second drop-down menu and display the loading status roomListSelect.innerHTML = '<option value="">Loading...'; //Reset the second drop-down menu if an invalid value is selected (such as the "Please select" option) if (selectedValue === "0" || selectedValue === "") { roomListSelect.innerHTML = '<option value="">Please select a valid office room'; return; } // Use the fetch API to send a POST request to the PHP script fetch('get_rooms.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: 'o_id=' selectedValue }) .then(response => { if (!response.ok) { throw new Error('Network response is abnormal' response.status); } return response.json(); }) .then(data => { // Clear all old options roomListSelect.innerHTML = ''; if (data. length > 0) { // Loop through the received data and create a new <option> for each data item data.forEach(room => { const option = document.createElement('option'); option.value = room.id; option.textContent = room.room_name; roomListSelect.appendChild(option); }); } else { roomListSelect.innerHTML = '<option value="">No meeting room available'; } }) .catch(error => { console.error('An error occurred while obtaining conference room data:', error); roomListSelect.innerHTML = '<option value="">Loading failed, please try again'; }); } </script> close(); ?>
get_rooms.php (server-side processing file): (The content is exactly the same as the get_rooms.php file provided earlier, make sure it is in the same directory as index.php or the path is correct)
<?php // get_rooms.php // Database connection configuration (please modify according to your actual situation) $servername = "localhost"; $username = "root"; $password = ""; $dbname = "your_database_name"; // Replace with your database name $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { // Error information should not be directly exposed in the production environment error_log("Database connection failed: " . $conn->connect_error); http_response_code(500); // Return the server's internal error status code echo json_encode(["error" => "Database connection failed"]); exit(); } //Set the response header to JSON header('Content-Type: application/json'); // Get the o_id parameter in the POST request $o_id = isset($_POST['o_id']) ? $_POST['o_id'] : ''; $rooms = []; // Array used to store query results if (!empty($o_id) && is_numeric($o_id)) { // Use prepared statements to prevent SQL injection $stmt = $conn->prepare("SELECT id, room_name FROM `assembly_hall` WHERE o_id = ? ORDER BY `room_name` ASC"); if ($stmt === false) { error_log("SQL preparation failed: " . $conn->error); http_response_code(500); echo json_encode(["error" => "Server internal error"]); $conn->close(); exit(); } $stmt->bind_param("i", $o_id); // "i" represents integer type $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $rooms[] = $row; } } $stmt->close(); } else { // If o_id is invalid or empty, you can return an empty array or error message // Keep returning an empty array, the front end will handle it} // Encode the result into JSON and output echo json_encode($rooms); $conn->close(); ?>
Things to note and best practices
- Security (SQL injection protection) : When processing database queries on the PHP backend, be sure to use prepared statements (Prepared Statements) . The PHP code of this tutorial has used $conn->prepare() and $stmt->bind_param() to prevent SQL injection, which is a crucial security measure.
- Error handling :
- Frontend : The .catch() block of the fetch API is used to catch network errors or JSON parsing errors. User-friendly error messages should be provided.
- Backend : The PHP script should check the database connection, query preparation and execution for success. In a production environment, detailed database error information should not be exposed directly to the client, but instead logged to a log file and generic error information returned to the client.
- User experience :
- Loading indicator : During the AJAX request, you can display a "Loading..." option in the second drop-down menu, or display a rotating loading icon to inform the user that data is being obtained.
- Disable the second drop-down menu : When the first drop-down menu has no valid selections or the data is loading, you can consider disabling the second drop-down menu to prevent users from misoperation.
- Initial state : Make sure the initial state of the second drop-down menu when the page loads is clear, such as "Please select an office first."
- Code organization :
- Keep your HTML files clean by placing your JavaScript code in a separate .js file and introducing it via .
- Encapsulate the database connection code into a separate file or class to facilitate management and reuse.
- HTTP method : This tutorial uses the POST method to send data as it is more suitable for sending form data and does not expose the data in the URL. For simple queries, you can also use the GET method, but you need to be aware of URL length restrictions and caching issues.
- Data format : AJAX usually uses JSON
The above is the detailed content of Dynamically loading drop-down menu: JavaScript gets selected value and interacts with PHP backend. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

When using Bootstrap for web page layout, developers often encounter the problem of elements being displayed side by side rather than stacked vertically by default, especially when the parent container applies Flexbox layout. This article will explore this common layout challenge in depth and provide a solution: by adjusting the flex-direction attribute of the Flex container to column, using Bootstrap's flex-column tool class to achieve the correct vertical arrangement of H1 tags and content blocks such as forms, ensuring that the page structure meets expectations.

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.
