HTML Drop Down List
Make an HTML drop down list with data received as JSON
Let's Learn
Step 1:
Create Index.php file and implement code as below
<h2 id="demo"></h2>
Step 2:
Create json_demo_db_post.php file and implement code as below.
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_POST["x"], false); $conn = new mysqli("localhost", "root", "", "farm_site"); if($obj->table == 'users') { $stmt = $conn->prepare("SELECT name FROM users LIMIT ?"); $stmt->bind_param("s", $obj->limit); $stmt->execute(); $result = $stmt->get_result(); } $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
Step 3:
Now we implement java script to create dropdown list based on json data and get data from database from php file.
<script> var obj, dbParam, xmlhttp, myObj, x, txt = ""; obj = { table: "users", limit: 20 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); txt += "<select class='form-control'>" for (x in myObj) { txt += "<option>" + myObj[x].name; } txt += "</select>" document.getElementById("demo").innerHTML = txt; } }; xmlhttp.open("POST", "json_demo_db.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script>
Complete Code For Making Drop Down List based On JSON Data Using JS
<!DOCTYPE html> <html> <head> <title>How To Make Drop Down List Based On JSON Data Using JS</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Make Drop Down List Based On JSON Data Using JS</h1> </div> <div class="well"> <h2 id="demo"></h2> </div> <script> var obj, dbParam, xmlhttp, myObj, x, txt = ""; obj = { table: "users", limit: 20 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); txt += "<select class='form-control'>" for (x in myObj) { txt += "<option>" + myObj[x].name; } txt += "</select>" document.getElementById("demo").innerHTML = txt; } }; xmlhttp.open("POST", "json_demo_db.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script> </div> </body> </html>