How to retrieve data from a database without reloading the page. We can use Ajax for retrieving data from a database without page reload. The data will be retrieved on javascript event. We will code in three part for getting records from a database without page reload.
First part:
We will code in <head> </head> section for calling function and sending data to PHP file by AJAX.
In HEAD section:
<!--get records without refresh page START-->
<!—Call JS file from googleapis-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function fetchRecords(searchItem, srvalue){
$.ajax({
url: 'check-price.php?searchItem='+searchItem, //call storeemdata.php to store form data
success: function(html) {
var ajaxShow = document.getElementById(srvalue);
ajaxShow.innerHTML = html;
}
});
}
</script>
<!--get records without refresh page END-->
Second part:
We will send search keyword by input tag in html <form> </form> by POST method. Look below and we will display output by id like <div id="displayrecord"></div>
In BODY section:
<form method="post">
Check item price:
<input type="text" name="searchItem" id="searchItem" onkeyup="fetchRecords(this.value, 'displayrecord')">
</form>
<div id="displayrecord"></div>
Third part:
We will code in PHP for getting records by searchable keyword. For this, we will connect database, after that we will get records by below mention code.
In PHP code:
<?php
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$connection = mysqli_connect('localhost','root','','db_name') or die('Error connecting to MySQL server.');
}
else
{
$connection = mysqli_connect('localhost','user_name','password','db_name') or die('Error connecting to MySQL server.');
}
$searchItem = $_GET['searchItem'];
if (isset($searchItem)) {
$query = "SELECT * FROM table_name WHERE columnone = '$searchItem' OR columntow = '$searchItem' GROUP BY columnone ";
$result = mysqli_query($connection, $query);
echo '<table border="1px solid black;" width="100%">';
echo '<tr>';
echo '<th width="50%">Item Name</th>';
echo '<th width="20%">SKU Code</th>';
echo '<th width="10%">MRP</th>';
echo '<th width="10%">Dicount Price</th>';
echo '<th width="10%">Discount</th>';
echo '</tr>';
while($row = mysqli_fetch_object($result)){
$discount = (($row->price-$row-> special_price)/$row-> price)*100;
echo '<tr>'
.'<td width="50%">'.$row->itemname.'</td>'
.'<td width="20%" align="center">'.$row->sku.'</td>'
.'<td width="10%" align="center">'.$row->price.'</td>'
.'<td width="10%" align="center"><font color="red"><b>'.$row->special_price.'</b></font></td>'
.'<td width="10%" align="center">'.round($discount).'%</td>'
.'</tr>';
}
echo '</table>';
}
mysqli_close($connection); // Connection Closed
?>