Fetching Data from Database Using AJAX and PHP

Photo by Growtika on Unsplash

Fetching Data from Database Using AJAX and PHP

In web development, it's common to fetch data from a database and display it dynamically on a web page without having to reload the entire page. AJAX (Asynchronous JavaScript and XML) allows us to achieve this by making asynchronous requests to the server, typically to fetch data in the background without disrupting the user experience. In this tutorial, we'll learn how to fetch data from a MySQL database using AJAX and PHP.

Prerequisites:

  • Basic knowledge of HTML, CSS, JavaScript, PHP, and MySQL.

  • A local or remote server environment with PHP and MySQL installed.

Step 1: Setting up the HTML Structure: We start by creating a basic HTML file that includes a container where the fetched data will be displayed. Here's the HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

<h2>Fetch Data using AJAX into PHP Script</h2>

<div id="result"></div>

<script>
// JavaScript code will go here
</script>

</body>
</html>

Step 2: Fetching Data Using AJAX: Next, we'll write JavaScript code to make an AJAX request to a PHP script that will fetch data from the database. We'll use jQuery for simplicity. Here's the JavaScript code:

$(document).ready(function(){
    function fetchData(username) {
        $.ajax({
            url: 'fetch_data.php',
            type: 'POST',
            data: { username: username },
            success: function(response){
                $("#result").html(response);
            },
            error: function(xhr, status, error){
                console.error(xhr.responseText);
            }
        });
    }

    var username = "your_username"; // Replace with actual username
    fetchData(username);

    setInterval(function() {
        fetchData(username);
    }, 5000);
});

Step 3: Creating the PHP Script: We'll create a PHP script (fetch_data.php) that connects to the database, fetches data based on the provided username, and returns it in JSON format. Here's the PHP code:

<?php
include 'config.php';

if(isset($_POST['username'])) {
    $username = $_POST['username'];

    $sql = "SELECT status FROM switch WHERE username='$username'";
    $result = mysqli_query($link, $sql);

    if ($result) {
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $estatus = $row["status"];
                echo $estatus;
            }
        } else {
            echo "No results found for username: " . $username;
        }
    } else {
        echo "Error executing SQL query: " . mysqli_error($link);
    }
} else {
    echo "Username parameter not provided.";
}

mysqli_close($link);
?>

Conclusion: In this tutorial, we learned how to fetch data from a MySQL database using AJAX and PHP. By making asynchronous requests to a PHP script, we were able to dynamically update the web page with the fetched data without having to reload the entire page. This approach enhances user experience and allows for more interactive web applications.

Feel free to customize and expand upon this example to suit your specific requirements!


This blog post provides a step-by-step guide along with the code snippets you provided, explanations, and suggestions for further customization.