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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<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> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?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(); } ?> |
1 2 3 4 |
<?php mysql_connect("","root"); mysql_select_db("todo"); ?> |
Enjoy it in GitHub as well! 🙂