Skip to content

Fetching data

You can use PHP to insert data from your database directly in your HTML. This is actually not a good habit, because it makes your code harder to read and maintain. It is better to separate your PHP code from your HTML code.

By using a template engine you can separate your PHP code from your HTML code. The template engine will then combine the two and send the result to the browser. The other way around is Javascript and AJAX. You can use Javascript to fetch data from your database and then insert it in your HTML. We are going to use Javascript and AJAX to fetch data from our database.

Html

Say we have a nice webpage where we want to display some data from our database. Maybe a counter of how many cats we have:

1
2
3
4
5
6
7
8
9
<html>
<head>
    <title>My cats</title>
</head>
<body>
    <h1>My cats</h1>
    <p>I have <span id="cat-counter">0</span> cats.</p>
</body>
</html>

Save this as cat.html.

What is important here is the id attribute of the span element. We will use this to identify the element in our Javascript code. This id attribute is unique, so we can only use it once in our HTML.

PHP

In our back-end we have to prepare the data for our front-end. We have to create a PHP file that will return the data we want to display. A format what is often used is JSON. JSON is a format that is easy to read for both humans and computers. It is also easy to convert to a Javascript object.

1
2
3
4
5
6
7
<?php

echo json_encode([
    'cat_counter' => 4,
]);

?>

Save this as cat.php.

Javascript

Now we have to fetch the data from our PHP file and insert it in our HTML. We can do this using the fetch-API. This is a Javascript API that allows us to fetch data from a URL. We can then use the data to update our HTML.

1
2
3
4
5
6
7
window.addEventListener('load', function() {
    fetch('cat.php')
        .then(response => response.json())
        .then(data => {
            document.getElementById('cat-counter').innerHTML = data.cat_counter;
        });
});

Save this as cat.js.

We tell the fetch-API to fetch the data from cat.php. We then tell it to convert the response to JSON. We then use the data to update our HTML. This happens when the page is loaded. We use the load event for this. This event is triggered when the page is loaded.

Use the script

Now we have to include our Javascript file in our HTML. We can do this by adding a script element to our HTML.

Update cat.html to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<html>
<head>
    <title>My cats</title>
    <script src="cat.js"></script>
</head>
<body>
    <h1>My cats</h1>
    <p>I have <span id="cat-counter">0</span> cats.</p>
</body>
</html>

Now we can open cat.html in our browser and see the result.