What is the Purpose of This Tutorial?
- How to Create Data Search and Display it to Textbox 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
- Basic
Tutorial Contents
In this tutorial, on how to create a data search from the database then display the data into a textbox. On this note, we will use the JQUERY plugin and take advantage of the AJAX programming language. With AJAX, we can perform a process without having to refresh / reload our web pages.
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,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
After that, insert some data into the student table.
INSERT INTO `student` (`id`, `name`, `sex`, `phone`, `address`) VALUES
('1457301010', 'Wahyu', 'Male', '+628989888', 'Bangkok'),
('1457301017', 'Jason', 'Male', '+62889999', 'Jakarta'),
('1457301020', 'Susan', 'Female', '+62881010', 'Singapore');
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"; // hostname
$user = "root"; // Username
$pass = ""; // Password (if you have, fill it)
$database = "searching"; // database name
$connect = mysqli_connect($host, $user, $pass, $database); // Connection to MySQL
?>
Step 3 - Create Form (VIew Page)
At this point, we will create a form page so that the data that will be searched will be displayed on this page. This page uses bootstrap css. Name it with index.php.
<html>
<head>
<title>GET DATA with AJAX</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script src="js/process.js"></script> (html comment removed: Load file process.js )
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Student Form <small>by simpleawesome</small></h1>
</div>
</div>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Form</h3>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">ID</label> <button type="submit" class="btn btn-primary" id="btn-search">Search</button>
<div class="col-sm-4">
<input type="text" class="form-control" id="id">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Sex</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="sex">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="phone">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Address</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="address">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Step 4 – AJAX
At this point, we will create the ajax script. Create a file named process.js. Here, I will explain the meaning of the program code directly using the comment beside the code.
function search(){
$("#loading").show(); // Show the loading
$.ajax({
type: "POST", // The method of sending data can be with GET or POST
url: "search.php", // Fill in url / php file path to destination
data: {id : $("#id").val()}, // data to be sent to the process file
dataType: "json",
beforeSend: function(e) {
if(e && e.overrideMimeType) {
e.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(response){ // When the submission process is successful
$("#loading").hide(); // Hide loading
if(response.status == "success"){ // If the content of the status array is success
$("#name").val(response.name); // set textbox with id name
$("#sex").val(response.sex); // set textbox with id sex
$("#phone").val(response.phone); // set textbox with id phone
$("#address").val(response.address); // set textbox with id address
}else{ // If the contents of the status array are failed
alert("undefined");
}
},
error: function (xhr, ajaxOptions, thrownError) { // When there is an error
alert(xhr.responseText);
}
});
}
$(document).ready(function(){
$("#loading").hide(); // Hide loading
$("#btn-search").click(function(){ // When the user clicks the Search button
search(); // Call search function
});
$("#id").keyup(function(){ // When the user presses a key on the keyboard
if(event.keyCode == 13){ // If user press ENTER key
search(); // Call search function
}
});
});
Step 5 - Search Process
In this last stage, we will create a php file that serves to process the search to the table of students in the database. Create a file with the name search.php.
<?php
include "connection.php"; // Load file connection.php
$id = $_POST['id']; // Retrieve id data sent via AJAX
$query = mysqli_query($connect, "SELECT * FROM student WHERE id='".$id."'"); // Show student data with the id
$row = mysqli_num_rows($query); // Calculate how much data from the $query execution results
if($row > 0){ // If the data is more than 0
$data = mysqli_fetch_array($query); // take the student's data
// BUat sebuah array
$callback = array(
'status' => 'success', // Set array status with success
'name' => $data['name'], // Set array name with the contents of the name field in the student table
'sex' => $data['sex'], // Set the sex array with the contents of the sex column in the student table
'phone' => $data['phone'], // Set array phone with phone column contents in student table
'address' => $data['address'], // Set the address array with the contents of the address field in the student table
);
}else{
$callback = array('status' => 'failed'); // set the status array with failed
}
echo json_encode($callback); // converting varibel $callback to JSON
?>
Step 6 - Run the Program
This is a page view to do the search process in it.
We will try to find the id that has been filled in the student table on the database that is: 1457301010. Here are the results :
Then try again search with different id that is: 1457301020.
When performing a search with a different id that is not in the database (or without input id), an error message will appear:
The search can also be done by pressing the enter key on the keyboard (without pressing the search button on the page) because there is the following command in the process.js file.
$("#id").keyup(function(){ // When the user presses a key on the keyboard
if(event.keyCode == 13){ // If user press ENTER key
search(); // Call search function
Little Explanation
- First, the User will input ID in the textbox with
id =" id "
.
<input type="text" class="form-control" id="id">
- Then when the user presses the Enter key or clicks the Search button,
<button type="submit" class="btn btn-primary" id="btn-search">Search</button>
function search ()
will execute the AJAX command (which is in the process.js file) to send the inputted ID to the search.php file. Then in the search.php file, a search of data to the student table in the database based on the ID sent earlier by AJAX. Then the search.php file will return the search result in the array of $callback
that has been converted to JSON. The array will be retrieved by AJAX and put it into the response variable. Then the last step is to set the textbox with the search results earlier.
Curriculum
- Change HTML Attribute with jQuery
- Adding Dynamic CSS Code with jQuery
- How to Create Searching Without Refresh Page with jQuery AJAX
Posted on Utopian.io - Rewarding Open Source Contributors
Your contribution cannot be approved because it is not as informative as other contributions. See the Utopian Rules. Contributions need to be informative and descriptive in order to help readers and developers understand them.
You can contact us on Discord.
[utopian-moderator]