In this article, we will discuss how to access the information available in the database using the AJAX. We will use the MySQL database, access the information stored in the database, and display the information on the webpage using the AJAX.
To perform this task we will create some sample entries in our MySQL database. Start the XAMPP control panel and start the MySQL service and open the MySQL Admin page.
MySQL Database: Click on new, create a new database, and name the database according to you.
Create a new table within the database.
Insert the following entries into the table.
Create the client-side PHP file which contains the AJAX request object and displays the result.
Client Side:
main.php: We have created a Student Database that contains the details of the student. We want to display this data based on the condition that the student's CGPA in DB should be equal to the user-entered CGPA input.
- In this PHP file, we have used basic HTML tags and created a form that accepts the user inputs and one submit button.
- When the user click submit button the JavaScript function ajax_fun() will be called. This function contains the required AJAX functions.
- The first line const ajax_Request = new XMLHttpRequest(); will create an AJAX HTTP request object.
- If AJAX requests status will be OK or 200. we are just changing the HTML content of the HTML div element with id "result-box"
document.getElementById("result-box").innerHTML = ajax_Request.responseText;
- We are sending the AJAX request to the server PHP page "index.php" along with the CGPA value that the user has entered.
var str = document.getElementById('cgpa_val').value;
ajax_Request.open("GET", "index.php?q="+str, true);
ajax_Request.send();
PHP
<!DOCTYPE html>
<html>
<head>
<style>
input {
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<h1 style="color:green;">GeeksforGeeks</h1>
<h3>Ajax Database operations</h3>
<hr><br>
<form>
<label> Enter the CGPA : </label>
<input type="text" name="stu_cgpa" id="cgpa_val">
<input type='button' onclick='ajax_fun()' value='Submit' />
</form>
<br>
<hr>
<div id="result-box">Result will display here</div>
<script language="javascript" type="text/javascript">
function ajax_fun() {
const ajax_Request = new XMLHttpRequest();
ajax_Request.onreadystatechange = function() {
if (ajax_Request.readyState == 4 && this.status == 200) {
document.getElementById("result-box").innerHTML =
ajax_Request.responseText;
}
}
var str = document.getElementById('cgpa_val').value;
ajax_Request.open("GET", "index.php?q=" + str, true);
ajax_Request.send();
}
</script>
</body>
</html>
Server Side:
index.php: We will create the server-side PHP file that will make a connection with the database to get the responses and will send the responses to the AJAX request object.
- We are creating the Database Connection using the following PHP function.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sampledb";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if($con->connect_error){
exit('Could not connect');
}
- If there will be an error in connection, con->connect_error will show to the user.
- We are storing the user-entered CGPA into another variable.
$cgpa = $_GET['q'];
- An SQL query will run on the DB and it will fetch the result from the DB and display the result in an HTML table.
PHP
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sampledb";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if($con->connect_error){
exit('Could not connect');
}
$cgpa = $_GET['q'];
$sql = "SELECT * FROM collegedb WHERE cgpa = '$cgpa' ";
$query = mysqli_query($con, $sql);
if (!$query) {
echo ("Error description: " . mysqli_error($con));
}
echo "<table border='1' style = 'border-collapse:collapse;'>
<tr>
<th style='padding:10px;'>FirstName</th>
<th style='padding:10px;'>LastName</th>
<th style='padding:10px;' >Rollno</th>
<th style='padding:10px;' >CGPA</th>
</tr>
";
if (mysqli_num_rows($query) > 0) {
while ($result = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td style='padding:10px;'>" .
$result['firstname'] . "</td>";
echo "<td style='padding:10px;'>" .
$result['lastname'] . "</td>";
echo "<td style='padding:10px;'>" .
$result['rollno'] . "</td>";
echo "<td style='padding:10px;'>" .
$result['cgpa'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
}
?>
Output:
Similar Reads
FastAPI - Crud Operations
We will explore how to implement CRUD operations with FastAPI. CRUD operations are essential in any web application, including creating new records, retrieving existing records, updating existing records, and deleting records from a database. What is CRUD in FastAPI?CRUD refers to the basic operatio
5 min read
Operation Name in GraphQL
In GraphQL, the operation name is a label that we attach to requests sent to servers which acts as an indication of code complexity. This allows us to define queries, mutations, and subscriptions to improve code readability and organize in particular when it comes to large projects making it easier
6 min read
What is data-ajax attribute?
The data-ajax attribute is a custom HTML attribute used for storing AJAX-related information in an element, guiding JavaScript interactions, and AJAX requests for dynamic content loading or updates. The data-ajax attribute allows to activation of unobtrusive AJAX. Unobtrusive AJAX is an add-on on jQ
3 min read
AJAX Browser Support
AJAX (Asynchronous Javascript and XML) is a very popular concept that is used to update the page without reloading the page.AJAX is also very popular because many top browsers support AJAX. Supporting AJAX means supporting XMLHttpRequest/ActiveXObject which will help us to send AJAX requests.Some of
5 min read
Backbone.js API Integration
Backbone.js is a lightweight library for structuring JavaScript code. It is also regarded as the MVC/MV* kind of framework. If you are not familiar with MVC, it is basically an architecture pattern for implementing user interfaces. Backbone.js also provides the concept called a router. It is used fo
3 min read
What is Ajax ?
Imagine browsing a website and being able to submit a form, load new content, or update information without having to refresh the entire page. That's the magic of AJAX. Asynchronous JavaScript and XML (AJAX) is a web development technique that allows web pages to communicate with a web server asynch
5 min read
Explain JSON in AJAX
AJAX is a very popular concept that is used to update the page without reloading the page. AJAX stands for Asynchronous Javascript And XML and because of that many Developers think that AJAX will only use XML to export and import data but that is not true. AJAX can use XML to transport any kind of d
5 min read
How To Use Ajax in WordPress?
Ajax (Asynchronous JavaScript and XML) is a powerful technique used in web development to create more responsive web applications. By using Ajax, you can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page. In WordPress, combini
3 min read
Read and Write to REST-Enabled Databases
Accessing and manipulating data stored in databases is a fundamental aspect of software development. With the advent of REST (Representational State Transfer) architecture, interacting with databases has become even more streamlined and accessible. In this article, we will explore the intricacies of
3 min read
AJAX Security
AJAX makes internet apps work easily without reloading the entire web page. But there are protection issues with AJAX that developers need to take care of it. In this article, we're going to talk about why securing AJAX is important. What is AJAX?AJAX stands for Asynchronous JavaScript and XML, It i
5 min read