How to Load Data From Database Without Page Refresh using Ajax, jQuery, and PHP

In this tutorial, you will learn how to load data from database without page refresh using ajax, jquery, mysql and PHP. The data will be retrieved on jquery event. Suppose we have a “student” table that contains an age and course and a “student” table that contains whole student information

HTML and jQuery Code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">

            function loaddata()
            {
                var name = document.getElementById("username");

                if (name)
                {
                    $.ajax({
                        type: 'post',
                        url: 'get.php',
                        data: {
                            user_name: name,
                        },
                        success: function (response) {
                            $('#display_info').html(response);
                        }
                    });
                } else
                {
                    $('#display_info').html("Please Enter Some Words");
                }
            }

        </script>

    </head>
    <body>
        <input type="text" name="username" id="username" onkeyup="loaddata();">
        <div id="display_info" ></div>
    </body>
</html>

PHP Code (get.php)

<?php

define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);


if (isset($_POST['user_name'])) {

    $name = $_POST['user_name'];
    $selectdata = " SELECT age,course FROM student WHERE name LIKE '$name%' ";
    $query = mysqli_query($con,$selectdata);
    while ($row = mysqli_fetch_assoc($query)) {
        echo "<p>" . $row['age'] . "</p>";
        echo "<p>" . $row['course'] . "</p>";
    }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *