You can use AJAX to interact with the database present on the server. The following example will demonstrate how a web page can fetch data from the database with the help of AJAX-
products.html
<html> <head> <title>Example of AJAX Database by Tutorialsandyou</title> <script type="application/javascript"> function fetchData(value) { if(value!=""){ var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if(this.readyState == 4){ document.getElementById("mobile-info").innerHTML = this.responseText; } }; request.open("GET", "/test/mobiles.php?q="+value, true); request.send(); } } </script> </head> <body> <select id="mydropdown" onchange="fetchData(this.value)"> <option value="">Select Mobiles</option> <option value="1">Samsung Galaxy J7</option> <option value="2">Motorola G5</option> </select> <div id="mobile-info"></div> </body> </html>
When a user selects any one of the mobiles from the dropdown, an event is fired which is handled by fetchData() function. This function creates an XMLHttpRequest object and sends a request to the server. Once a response is received from the server, it is shown to you by updating HTML and CSS.
mobiles.php
<?php $id=$_GET['q']; $conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMORE_EXCEPTION); $sql="SELECT name, price, screen_size FROM mobiles WHERE id=".$id; $rows=$conn->query($sql); if($row){ ?> <table> <tr> <th>Name</th> <th>Price</th> <th>Screen Size</th> </tr> <tr> <td><?php echo $row['name']; ?></td> <td><?php echo $row['price']; ?></td> <td><?php echo $row['screen_size']; ?></td> </tr> </table> <?php } ?>
This page receives the AJAX request and calls database to get data of selected mobile. Once the data is received from the database, it is placed in the table element and send to the browser.
Output