I’m implementing a multiple dropdown menu that retrieves data from a MySQL database using PHP and JavaScript. The issue arises when the page first loads, as I encounter an error indicating that the $_POST array is undefined, which is essential for executing my MySQL query and displaying the related chart.
The error message I’m seeing is: “Warning: Undefined array key ‘titulos’ …”. After my first form submission, everything works correctly.
How can I establish a default value for this $_POST variable to prevent the error? Here’s part of my form:
<form name="myform" action="" method="post" style="text-align:center;margin-top:2%;">
<select name="magazines" style="font-size:16px;" onclick="getSeries(this.value)">
<option value="">Choose a Magazine</option>
<?php
$magazines = getMagazines();
foreach($magazines as $magazine){
echo '<option value="'.$magazine['magazine_code'].'">'.$magazine['Magazine_name'].'</option>';
}
?>
</select>
<select name="titulos" style="font-size:16px;">
<option value="">Choose a Series</option>
</select>
<input type="submit" value="Send" style="font-size:16px;">
<?php
$series_tit = $_POST['titulos'];
$query = "SELECT * FROM chartdata WHERE Serie_name = '$series_tit'";
?>
</form>
The PHP functions I’m using are:
function getMagazines() {
$conn = databaseConnection();
$res = $conn->query("SELECT * FROM categorias");
while ($row = $res->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
if (isset($_GET["magazine_code" ])) {
echo getSeries($_GET["magazine_code"]);
}
function getSeries($magazine_code) {
$conn = databaseConnection();
if (!$conn) {
return false;
}
$magazine_code = htmlspecialchars($magazine_code);
$res = $conn->query("SELECT * FROM chartdata WHERE magazine_code ='$magazine_code'");
while ($row = $res->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
Here’s how my JavaScript function looks:
function getSeries(magazineCode) {
const seriesDropDown = document.forms["myform"].titulos;
if (magazineCode.trim() === "") {
seriesDropDown.disabled = true;
seriesDropDown.selectedIndex = 0;
return false;
}
fetch(`functions_sales.php?magazine_code=${magazineCode}`)
.then(response => response.json())
.then(function(series) {
let options = '<option value="">Choose a Series</option>';
for (let sery of series) {
options += `<option value="${sery['Serie_name']}">${sery['Serie_name']}</option>`;
}
seriesDropDown.innerHTML = options;
seriesDropDown.disabled = false;
});
}
I’ve attempted to set a default selected option in the dropdown, but I’m still facing the same warning when the page loads.