Load Data From Database Without Page Refresh Using Ajax and jQuery
Last Updated : Apr 15, 2022
IN - Ajax JavaScript jQuery PHP MySQL
In this tutorial we will teach you how to load the data from database without page refresh and then
display the data using Ajax and jQuery.
You only need to download jQuery to get the data from
database without page refresh.
You may also like load data from database on page scroll.
To Load the data from database without page refresh it takes only two steps:-
- Make a HTML form to load the data
- Connect to the database and send data
Step 1. Make a HTML form to load the data
We make a HTML form with post method and save it with a name displaydata.html
<html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> function loaddata() { var name=document.getElementById( "username" ); if(name) { $.ajax({ type: 'post', url: 'loaddata.php', data: { user_name:name, }, success: function (response) { // We get the element having id of display_info and put the response inside it $( '#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>
You can do validation to make your code more secure or you can view our How to do validation before and after submitting the form tutorial.
Step 2. Connect To The Database and Send Data
In this step we connect to our sample database named student and it has a table named student_info which has 3 columns name, age, course and then we query the database and get desired results.
// loaddata.php <?php if( isset( $_POST['user_name'] ) ) { $name = $_POST['user_name']; $host = 'localhost'; $user = 'root'; $pass = ' '; mysql_connect($host, $user, $pass); mysql_select_db('student'); $selectdata = " SELECT age,course FROM student_info WHERE name LIKE '$name%' "; $query = mysql_query($selectdata); while($row = mysql_fetch_array($query)) { echo "<p>".$row['age']."</p>"; echo "<p>".$row['course']."</p>"; } } ?>
Whatever this page echo's it display on the displaydata.html page. You can also view load more results from database using ajax.
That's all, this is how to load data from database without page refresh using Ajax and jQuery. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.
Latest Tutorials
- Create Animated Skill Bar Using jQuery, HTML And CSS
- Simple And Best Responsive Web Design Using CSS Part 2
- Show Button On Hover Using HTML And CSS
- Material Design Login Form Using jQuery And CSS
- Animated Progress Bar Using jQuery And CSS
- Dynamic Drop Down Menu Using jQuery, Ajax, PHP And MySQL
- Get Website Statistics Using PHP, jQuery And MySQL
- HTML5 Login And Signup Form With Animation Using jQuery
- Facebook Style Homepage Design Using HTML And CSS
- View Webpage In Fullscreen Using jQuery