All TalkersCode Topics

Follow TalkersCode On Social Media

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

Retrieve Data From MySQL Database Using JavaScript

Last Updated : Mar 11, 2024

Retrieve Data From MySQL Database Using JavaScript

In this article we will show you the solution of retrieve data from MySQL database using JavaScript, now we have to create a database first on the Localhost server.

After adding some data there we can connect the MySQL server by using AJAX, JavaScript, and PHP.

Mysqli () method: this function is used to connect the MySQL server.

Syntax:

$con = new mysqli (host, username, password, dbname)

Step By Step Guide On Retrieve Data From MySQL Database Using JavaScript :-

<!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.0 " >
    <title> retrieve data from MySQL database using JavaScript </title>
    <style>
        body {
            font-family : 'Lucida Sans' , 'Lucida Sans Regular' , 'Lucida Grande' , 'Lucida Sans Unicode' , Geneva , Verdana , sans-serif ;
        }
        h1 {
         font-size : larger ;
         font-weight : bolder ;
         color : rgb(113, 221, 113) ;
         text-align : center ;
        }
        h3 {
            text-align : center ;
        }
    </style>
</head>
<body>
    <h1> TALKERSCODE </h1>
    <h3> retrieve data from MySQL database using JavaScript </h3>
    <table>
        <tr>
            <th scope="col"> ID </th>
            <th scope="col"> Name </th>
            <th scope="col"> Age </th>
            <th scope="col"> Email </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 id = data[a].ID ;
                    var name = data[a].name ;
                    var age = data[a].age ;
                    var email = data[a].email ;
                    html += "<tr>" ;
                        html += "<td>" + ID + "</td>" ;
                        html += "<td>" + name + "</td>" ;
                        html += "<td>" + age + "</td>" ;
                        html += "<td>" + email + "</td>" ;
                    html += "</tr>" ;
                }
                document.getElementById("data").innerHTML = html ;
            }
        }
    </script>
</body>
</html>
  1. First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in.
  2. Secondly, the <html> tag is used to indicate the beginning of an HTML document.
  3. As above now the <head> tag is used to contain information about the web page. In this tag, a <title> tag is used which helps us to specify a webpage title.
  4. Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
  5. Thirdly, the <body> tag is used to define the webpage body. All the contents to show on the website are written here.
  6. <h1> tag used to add heading here.
  7. Created the <style> tag to add CSS to the HTML page.
  8. <table> to creating table and add heading <tr> as the MySQL database heading
  9. Create a <tbody> with the id ‘data’. In this <tbody> the mySQL database is shown as an HTML table.
  10. To add JavaScript Create a <script> tag.
  11. To call ajax creating variables for ajax, method, url, asynchronous
  12. Using open() method with the variable above
  13. Send() method to send ajax request
  14. For receiving a response from data.php use the ‘.onreadystatechange()’ method equal to a function. With the function using if statement to convert JSON back to array
  15. Get the html value for the table. Using loop through the data
  16. Getting the <tbody> by its id with .innerHTML tag to display the table.

PHP Code for data.php:

<?php
$conn = mysqli_connect("localhost", "root", "", "list") ;
$result = mysqli_query($conn, "SELECT * FROM persons") ;
$data = array () ;
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row ;
}
echo json_encode ($data) ;
?>
  1. We write <?php tag to write PHP within it.
  2. Creating a connection with $con with mysqli() function with hostname, user name, password, and database name.
  3. Using mysqli_fetch_assoc() to fetch the data as a row
  4. Json_encode() the returning data in the format of JSON.
  5. ?> to close the php code.

Conclusion :-

At last, here in conclusion, here we can say that with this article’s help, we know how to get retrieve data from MySQL database using JavaScript.

I hope this article on retrieve data from MySQL database using JavaScript helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪