All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Fetch Data From Database In JavaScript Using Ajax

Last Updated : Mar 11, 2024

How To Fetch Data From Database In JavaScript Using Ajax

In this tutorial we will show you the solution of how to fetch data from database in JavaScript using ajax, in database SQL Server we created table with some information we need to fetch them to display on webpage.

For achieve this we need to make connection between server and client side those are achieved only using php.

Because php is a server side language it supports our connection execution so when our server request success then we can fetch any data from database.

In javascript we achieve this by ajax. Ajax has XMLHttpRequest object to communicate with servers. It can send and receive information in various formats including JSON, XML, HTML and text files.

Step By Step Guide On How To Fetch Data From Database In JavaScript Using Ajax :-

In ajax we used ‘XMLHttpRequest’ object for collects data from database. For generating connection with sql server we need to use php server side language.

In php we collects server information like, ‘server_name,user_name,password,database_name’ for execute connection with server and executing query to fetch all data from table ‘employee’ encoded to html webpage.

Index.php

<!DOCTYPE html>
<html>
    <head><title>fetching data from database</title></head>
    <body>
<table border = 1 cellpadding = 10>
    <tr><th>Fname</th><th>Lname</th></tr>
    <tbody id="data"></tbody>
</table>
<script>
    var ajax=new XMLHttpRequest();
    var method="GET";
    var url="data.php";
    var asynchronous=true;
    ajax.open(method,url,asynchronous);
    ajax.send();
    ajax.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            var data = JSON.parse(this.responseText);
            console.log(data);
            var html="";
            for(var a=0;a<data.length;a++){
                var fn=data[a].fname;
                var ln=data[a].lname;
                html+="<tr>";
                html+="<td>"+fn+"</td>";
                html+="<td>"+ln+"</td>";
                html+="</tr>";
            }
            document.getElementById("data").innerHTML=html;
        }
    }
</script>
</body>
</html>

Data.php

<?php
$conn = mysqli_connect("localhost","root","","dbase");
$res=mysqli_query($conn,"SELECT * FROM employee");
$data=array();
while ($row=mysqli_fetch_assoc($res)){
    $data[]=$row;
}
echo json_encode($data);
?>
  1. <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
  2. The<html> tag is used to indicate the beginning of HTML document.
  3. As above shown <head> tag is contain information about webpage and some websites when need to use external files those links are declared here. <title> tag is used for set the webpage title.
  4. Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
  5. <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
  6. We are created <table> with header row, two columns and one table body <tbody> tag used for updates all database data.
  7. In <script> we created XMLHttpRequest object name is ‘ajax’ for request data from server. In script for opening file in server we using ‘ajax.open()’ method and it has three parameters.
  8. Those parameter contains ‘type of method, file url, asynchronous Boolean value’ information and we stored those parameters to variables ‘method,url,asynchronous’.
  9. Here we are fetching data from server so we used ‘GET’ method, url contain ‘data.php’ it has database connection code.
  10. The open() method specifies the type of request for server and send() method sends request to the server.
  11. The onreadystatechange property defines a function to be executed when the readyState changes and when readyState, status equal to respective values 200, 4 it denotes server is ready for serve.
  12. The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. Using this function string stored to variable ‘data’ and using for loop fetched values are stored to respective variable ‘fn and ln’.
  13. Then appends to table row with respective column and side by side stored to html variable. When for loop finished all retrieved data appends to table body with id ‘data’ by innerHTML.
  14. Both </body>,</html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
  15. Before writing data.php file we need to create database ‘dbase’ on mysql server then create a table with two columns namely fname, lname then table name is ‘employee’.
  16. In data.php Mysqli_connect() function used for create new connection and its stored into variable $conn, It has all server informations. mysqli_query() function performs a query against a database. This method executing select query for collects all data from table.
  17. Array variable ‘$data’ created for store all fetched data’s and fetched by while loop with function ‘mysqli_fetch_assoc()’. Then printed using ‘json_encode()’ method.

Conclusion :-

This topic helps you for fetching data from database using ajax. When user inserting data’s to database and in webpage all database data’s are updated on html table.

Using javascript, php and database we can collect and maintain more types of information like students personal information, students mark detail, office employee details, salary details and secure informations, etc..,

In conclusion now we able to connect server using php, javascript only.

I hope this tutorial on how to fetch data from database in JavaScript using ajax helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪