PHP – JQuery – MySQL – Make a simple drop down menu
After the simple ToDo list here, I have decided to add more features to it. So, a possible feature, looks like this – you have a drop down menu with all the users in the database:

Then, after a selection, you get a list of their todo tasks:
That is the whole story. 🙂 So how it is built? Once the file “form_ajax.php” is loaded, we connect to the mySQL database, where we take the values for the optional button through php code. Once the optional button is changed, a JQuery function “change” is loaded, which does the following:
- Tries to get the value of the file data.php.
- In order to get it, in the data.php, we make a query to the db, with the id of the selected option.
- At the end JQuery displays what we have.
And that is how the long story looks short. The code comes here:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" ></script>
<script>
$(function(){
$('#users').change(function(){
$.get(
"data.php",
{choice:$(this).val()},
function(data){
$('#my_field').html(data);
});
});
});
</script>
<style>
#my_field{
font-family:verdana;
background-color:yellow;
}
body{
color:RGB(0,189,255);
}
label{
color:blue;
}
</style>
</head>
<body>
<form>
<p>
<label for="users">Lists of users</label>
<select id="users" name="users">
<option value="">Choose</option>
<?php
include "db_connection.php";
$SQL = "SELECT DISTINCT(user_id) FROM todos";
$my_result = mysql_query($SQL);
$counter = 1;
while ($data = mysql_fetch_assoc($my_result))
{
echo "<option value=$data[user_id]>User $counter</option>";
$counter++;
}
?>
</select>
</p>
</form>
<div id="my_field"></div>
</body>
</html>
<?php
include 'db_connection.php';
function getTodoItems($user_id){
$SQL = "SELECT * FROM todos WHERE user_id = ". $user_id . "";
$result = mysql_query($SQL);
echo "<form action='#' method = 'POST'>";
while($data = mysql_fetch_assoc($result))
{
echo "<table>";
echo "<tr>";
echo "<td><input type='checkbox' name='check_list[]' value='". $data["id"] ."'></td>";
echo "<td>" . $data["todo_item"] . "</td>";
echo "</tr>";
echo "</table>";
}
echo "</hr>";
echo "</form>";
}
function getCleared(){
echo "Please, select a user with a todo list :)";
}
if($_GET["choice"]){
echo getTodoItems($_GET["choice"]);
}else{
echo getCleared();
}
?>
<?php
mysql_connect("","root");
mysql_select_db("todo");
?>
Enjoy it in GitHub as well! 🙂
