Ajax Show Database Data in php

 <?php

$servername = "localhost";
$username = "root";
$password = "";
$database = "test";

//Create Connection
$conn = new mysqli($servername, $username, $password, $database);

//Check Connection
if ($conn->connect_error) {
    die("Connection failed : " . $conn->connect_error);
}
Above is mysqli_conn.php File which is included in below shown files.







Below is ajax-load.php File.
<?php
include("mysqli_conn.php");

$sql = "SELECT * FROM students";
$result = $conn->query($sql);
$output = "";

if ($result->num_rows > 0) {
    $output = "<table border='1' width='100%' cellspacing='0' cellpadding='10px'>
                <tr>
                    <th>Id</th>
                    <th>Student Name</th>
                    <th>Age</th>
                    <th>City</th>
                </tr>";
    while ($row = $result->fetch_assoc()) {
        $output .= "<tr><td>{$row['id']}</td><td>{$row['student_name']}</td><td>{$row['age']}</td><td>{$row['city']}</td></tr>";
    }
    $output .= "</table>";
    $conn->close();
    echo $output;
} else {
    echo "<h2>No Record Found.</h2>";
}







Below is show-data.php File.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="jquery-3.7.1.min.js"></script>
</head>

<body>
    <table id="main" border="0" cellspacing="0">
        <tr>
            <td id="header">
                <h1>PHP with Ajax</h1>
            </td>
        </tr>
        <tr>
            <td id="table-load">
                <input type="button" id="load-button" value="Load Data"><br><br>
            </td>
        </tr>
        <tr>
            <td id="table-data">
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="js/jquery.js"></script>
    <!-- Whenever we use Ajax, there is no need to use <Form> and
     also no need to use method "GET" or "POST" -->
    <script type="text/javascript">
        $(document).ready(function() {
            $("#load-button").on("click", function(e) {
                $.ajax({
                    url: "ajax-load.php",
                    type: "POST",
                    success: function(data) {
                        $("#table-data").html(data);
                    }
                });
            });
        });
    </script>
</body>

</html>




Comments

Popular posts from this blog

Ajax Insert Records in Database Tutorial in PHP

SubQuery with EXISTS and NOT EXISTS in PHP

Submitting HTML Form data in JSON File (without MySql Database) in PHP