Skip to content

Instantly share code, notes, and snippets.

@biplab3
Created May 12, 2020 09:54
Show Gist options
  • Save biplab3/2b4009538b2cab816dd8936475369618 to your computer and use it in GitHub Desktop.
Save biplab3/2b4009538b2cab816dd8936475369618 to your computer and use it in GitHub Desktop.
<?php
include('connect.php');
if(isset($_POST['search'])){
$key = $_POST['search'];
$stmt = $con->prepare("select * from users where username like '%$key%' or phone_no like '%$key%'");
$stmt->execute();
$user_details = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()>0)
{
$output['success'] = '<table class="table table-bordered">
<thead>
<th>Sl No.</th>
<th>Username</th>
<th>Phone No</th>
<th>Email</th>
<th>Password</th>
</thead>
<tbody>
<tr>
<td>'.$user_details['id'].'</td>
<td>'.$user_details['username'].'</td>
<td>'.$user_details['phone_no'].'</td>
<td>'.$user_details['email'].'</td>
<td>'.$user_details['password'].'</td>
</tr>
</tbody>
</table>';
echo json_encode($output);
}
else
{
$output['failed'] = '<font color="#ff0000" style="font-size: 20px;">Data not available</font>';
echo json_encode($output);
}
exit;
}
?>
<html>
<head>
<title>ajax example</title>
<link rel="stylesheet" href="bootstrap.css" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="bootstrap-theme.css" crossorigin="anonymous">
<style>
.container{
width:50%;
height:30%;
padding:20px;
}
</style>
</head>
<body>
<div class="container">
<h3><u>How to search data from database using ajax jquery in PHP</u></h3>
<br/><br/>
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<label for="name">Search information:</label>
<input type="search" class="form-control" onkeyup="fetchData()" id="find" placeholder="fill the information">
</div>
</div>
</div>
<br/><br/>
<h3><u>Search Result</u></h3><br/>
<div id="comehere"></div>
</div>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.min.js"></script>
<script>
function fetchData(){
var search = $('#find').val();
//alert(search);
if(search){
$.ajax({
url: 'ajaxsearch.php',
type: 'post',
data: {
'search': search
},
dataType: 'json'
})
.done(function(data){
if(data.success)
{
$('#comehere').html(data.success);
}
else
{
$('#comehere').html(data.failed);
}
})
.fail(function(data){
alert(data);
});
}
else{
$('#comehere').html('');
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment