All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Load Data From Database Without Page Refresh Using Ajax and jQuery

Last Updated : Jul 1, 2023

IN - Ajax JavaScript jQuery PHP MySQL | Written & Updated By - Anjali

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.

Load Data From Database Without Page Refresh Using Ajax and jQuery

To Load the data from database without page refresh it takes only two steps:-

  1. Make a HTML form to load the data
  2. 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.

I hope this tutorial on load more data without page refresh helps you and the steps and method mentioned above are easy to follow and implement.