To create a dynamic dropdown menu using AJAX and jQuery, follow these steps:
<head>
tag:<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select>
element in your HTML file, which will serve as the dropdown menu. Give it an ID to reference it later. For example:<select id="dynamic-menu"></select>
$.ajax()
method to make a GET request to a server-side script called getData.php
. This script should return JSON data containing the options for the dropdown menu.$.ajax({
url: "getData.php",
method: "GET",
dataType: "json",
success: function(data) {
// Process the JSON data and populate the dropdown menu
var options = "";
$.each(data, function(key, value) {
options += "<option value='" + value + "'>" + value + "</option>";
});
$("#dynamic-menu").html(options);
}
});
getData.php
in this example) that fetches the dynamic data from a data source (e.g., a database) and returns it as JSON. For example:<?php
// Fetch data from a database
$data = array("Option 1", "Option 2", "Option 3");
// Return the data as JSON
echo json_encode($data);
?>
error
callback function to the $.ajax()
method.That's it! When you load your HTML file, the jQuery AJAX function will retrieve the dynamic data from the server-side script and populate the dropdown menu with the options returned in the JSON response.