How to Create Searching Without Refresh Page with jQuery AJAX
What is the Purpose of This Tutorial?
- How to Create Searching Without Refresh Page with jQuery AJAX
Requirements
- Knowledge about HTML, CSS, PHP and Javascript
- Bootstrap 3 or 4 version
- jQuery (.js file), you can download it in this link https://jquery.com/download/
- XAMPP (or only any MySQL application on your pc)
Difficulty
- Intermediate
Tutorial Contents
In this tutorial, I will share a tutorial on How to Find data/search without refreshing the page by using jQuery AJAX. This method will be very easy for website users, because it does not need to wait for web content such as text or images to search. When you click the search button results will be displayed on the same page and without refresh the page first because it held its name AJAX.
So, Let's get started.
Step 1 - Make a Database
Here we will create a database with the name searching. Then create a table with the name student.
CREATE TABLE IF NOT EXISTS `student` (
`id` varchar(11) NOT NULL,
`name` varchar(50) NOT NULL,
`sex` varchar(10) NOT NULL,
`phone` varchar(15) NOT NULL,
`address` text NOT NULL,
`photo` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
)
After that, insert some data into the student table.
INSERT INTO `student` (`id`, `name`, `sex`, `phone`, `address`, `photo`) VALUES
('10110470110', 'Simpleawesome', 'Male', '8199288272', 'California', '09032017041439client1.png'),
('10110470111', 'Susan', 'Female', '89228827727', 'New Jersey', 'tab2.png'),
('10110470112', 'David', 'Male', '8561777166', 'Sidney', 'man2.jpg'),
('10110470113', 'Ashanty', 'Female', '828817717', 'Jakarta', 'team-member.jpg'),
('10114072001', 'Takasugi Yamada', 'Male', '89283773622', 'Tokyo', 'man1.jpg');
Please note, in the photo field, we enter the file name of some photos we have provided in the photo folder.
Step 2 - Create a Database Connection
Create a file for the database connection so that the database we created can connect with php.
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'searching';
$pdo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
?>
Here, we use PDO (PHP Data Object) to connect and query to its MySQL database, because PDO has advantages that support 12 Database Types with the same script. Only a few query changes. the shortcomings that can only be used with Object Oriented model.
Step 3 - Create a View Page
The next step is to make 1 piece of useful file as the main template. Create a file with the name index.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live SEARCH</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.align-middle{
vertical-align: middle !important;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#" style="color: white;"><b>Live Search with jQuery AJAX</b></a>
</div>
<p class="navbar-text navbar-right hidden-xs" style="color: white;padding-right: 10px;">
FOLLOW US ON
<a target="_blank" style="background: #3b5998; padding: 0 5px; border-radius: 4px; color: #f7f7f7; text-decoration: none;" href="">Facebook</a>
<a target="_blank" style="background: #00aced; padding: 0 5px; border-radius: 4px; color: #ffffff; text-decoration: none;" href="">Google+</a>
<a target="_blank" style="background: #fff; padding: 0 5px; border-radius: 4px; color: #d34836; text-decoration: none;" href="">YouTube</a>
</p>
</div>
</nav>
<div style="padding: 0 15px;">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search..." id="keyword">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" id="btn-search">SEARCH</button>
<a href="" class="btn btn-warning">RESET</a>
</span>
</div>
</div>
</div>
<br>
<div id="view"><?php include "view.php"; ?></div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
In the above code, we will load the required library / plugin like Jquery and Bootstrap. And we also load an ajax.js file that we will create in the next step.
Then in the code above index.php, see the code There is <? php include "view.php"; ?> The code serves to load the view.php file whose contents are the tables that hold the data from the query results to the student table in the database. Now we will try to create the file. Create a file with the name view.php.
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th class="text-center">Number</th>
<th class="text-center">Photo</th>
<th>ID</th>
<th>NAME</th>
<th>SEX</th>
<th>PHONE</th>
<th>ADDRESS</th>
</tr>
<?php
include "connection.php";
if(isset($keyword)){
$param = '%'.$keyword.'%';
$sql = $pdo->prepare("SELECT * FROM student WHERE id LIKE :id OR name LIKE :na OR sex LIKE :sx OR phone LIKE :ph OR address LIKE :a");
$sql->bindParam(':id', $param);
$sql->bindParam(':na', $param);
$sql->bindParam(':sx', $param);
$sql->bindParam(':ph', $param);
$sql->bindParam(':a', $param);
$sql->execute();
}else{
$sql = $pdo->prepare("SELECT * FROM student");
$sql->execute();
}
$no = 1;
while($data = $sql->fetch()){
?>
<tr>
<td class="align-middle text-center"><?php echo $no; ?></td>
<td class="align-middle text-center">
<img src="photo/<?php echo $data['photo']; ?>" width="80" height="80">
</td>
<td class="align-middle"><?php echo $data['id']; ?></td>
<td class="align-middle"><?php echo $data['name']; ?></td>
<td class="align-middle"><?php echo $data['sex']; ?></td>
<td class="align-middle"><?php echo $data['phone']; ?></td>
<td class="align-middle"><?php echo $data['address']; ?></td>
</tr>
<?php
$no++;
}
?>
</table>
</div>
A little explanation for the code view.php above :
include "connection.php";
Means, The code serves to load the connection.php file.
$param = '%'.$keyword.'%';
$sql = $pdo->prepare("SELECT * FROM student WHERE id LIKE :id OR name LIKE :na OR sex LIKE :sx OR phone LIKE :ph OR address LIKE :a");
$sql->bindParam(':id', $param);
$sql->bindParam(':na', $param);
$sql->bindParam(':sx', $param);
$sql->bindParam(':ph', $param);
$sql->bindParam(':a', $param);
$sql->execute();
Means, The code serves to query the database and execute it. In the example above, we will perform a query to display student data based on one component (Based on id / Name / Sex / Phone / Address).
$sql = $pdo->prepare("SELECT * FROM student");
$sql->execute();
Means, This code is useful for displaying all data from the student table.
$data = $sql->fetch()
Means, The code serves to retrieve all query data and hold the data in an array and save it into the $data variable. The code we store in a while(...) code that serves to perform the process of looping until the last data with the aim that we can display the data one by one.
<tr>
<td class="align-middle text-center"><?php echo $no; ?></td>
<td class="align-middle text-center">
<img src="photo/<?php echo $data['photo']; ?>" width="80" height="80">
</td>
<td class="align-middle"><?php echo $data['id']; ?></td>
<td class="align-middle"><?php echo $data['name']; ?></td>
<td class="align-middle"><?php echo $data['sex']; ?></td>
<td class="align-middle"><?php echo $data['phone']; ?></td>
<td class="align-middle"><?php echo $data['address']; ?></td>
</tr>
In the above code there is a variable $data used to retrieve the contents of the fields that exist in the student table in database searching. In the code above there is also a code that is on the sign ['......'], the code must be the same as the field name in the student table.
Step 4 - Ajax
Next we will create an ajax file that serves to send data to the file search.php process that we will later create in the next step. Now create a new file with the name ajax.js.
$(document).ready(function(){
$("#btn-search").click(function(){
$(this).html("SEARCHING...").attr("disabled", "disabled");
$.ajax({
url: 'search.php',
type: 'POST', // Tentukan type nya POST atau GET
data: {keyword: $("#keyword").val()}, // Set data yang akan dikirim
dataType: "json",
beforeSend: function(e) {
if(e && e.overrideMimeType) {
e.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(response){
$("#btn-search").html("SEARCH").removeAttr("disabled");
$("#view").html(response.result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
a little explanation from code above :
url: filled with url file to be addressed.type: filled with the method you want to use. fill with GET or POST.data: data to be sent to the intended file.success: function () {}: when the sending process is complete, do the action.error: function () {}: when an error occurs, do the action.
Step 5 - Searching Process
The final step is to create a file for PHP to process its search. Create a file with the name search.php.
<?php
// Retrieve keyword data sent with AJAX
$keyword = $_POST['keyword'];
// Load view.php
ob_start();
include "view.php";
// Put the contents of view.php into the $html variable
$html = ob_get_contents();
ob_end_clean();
// Create an array with the result index and its value $html
// Then convert to JSON
echo json_encode(array('result'=>$html));
?>
The following file structure in the folder or outside the folder based on the code we have created earlier.
Step 6 - Run the Program
Here's the look for the search we've created. In it will be displayed all the tables.

Then we do search by name that is "Ashanty". This is the search result:
We try to do a search based on the address of "California". Here are the results:
The other, we try to use sex (female) for search. Here are the results:
So also with other keywords, if we search based on the keywords we want it will appear in accordance with the keywords inputted.
Note that the page will not switch to a new page when searching because search results will also appear on the index.php page.
Curriculum
Posted on Utopian.io - Rewarding Open Source Contributors





Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Thank you
Hey @simpleawesome I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x