I have the following code for a multiple dropdown menu, which takes the data from mysql database, then depending on the choice, displays a another dropdown menu.
I have done this with php, javascript and MySQL.
The problem I come across is that the first time I load the page I get the error that the array, that comes from $_Post, is not created. Such array enables the mysql query and following chart to appear.
The error is:
“Warning: Undefined array key “titulos” … “
After I do one submission with the dropdown menu, everything works fine.
How can I create a default result for this variable?
Dropdown menu and Chart Query
<form style="text-align:center;margin-top:2%;" name="myform" action="" method="post"><select style="font-size:16px;" name="magazines" onclick="getSeries(this.value)">
<option value="">Choose a Magazine</option>
<?php
$magazines = getMagazines();
foreach($magazines as $magazine){
<option value="<?php echo $magazine['magazine_code'] ?>">
<?php echo $magazine['Magazine_name']?></option>
<?php
}
?>
</select>
<select style="font-size:16px;" name="titulos">
<option value="">Choose a Series</option>
</select>
<input style="font-size:16px;" value="Send" type="submit">
$series_tit =$_POST['titulos'];
$query = "SELECT * FROM chartdata WHERE Serie_name = '$series_tit'";
PHP functions
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);
}
And Javascript
function getSeries(magazineCode){
let 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 out = "";
out += `<option value="">Choose a Series</option>`;
for (let sery of series){
out += `<option value="${sery['Serie_name']}">${sery['Serie_name']}</option>`;
}
seriesDropDown.innerHTML = out;
seriesDropDown.disabled = false;
});
}
I’ve tried making a selected option into the form but the response continue being the same.