How to Load Data From Database Without Refresh Page Using Ajax and PHP

n this article, you will learn how to retrieve data from a database without refreshing the webpage. Suppose we have student table that contains an name and username and an student_info table that contains whole student information. You may also like Submit a form without using a submit button using JavaScript and How to upload image without refresh page using Ajax and PHP.

HTML Code

<input type="text" name="username" id="username" onkeyup="loaddata($(this).val());">
<div id="display_info" ></div>

Jquery Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
    function loaddata(name)
    {
         if(name != "")
        {
           $.ajax({
           type: 'post',
           url: 'load.php',
           data: {
            user_name:name,
           },
           success: function (response) {
            $( '#display_info' ).html(response);
           }
           });
        }
        else
        {
          $( '#display_info' ).html("Please Enter Some Words");
        }
    }
</script>

PHP Code (load.php)

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

Leave a Reply

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