To achieve your desired result, You need to utilize Ajax
and JSON
.
Your PHP script will return fresh data as json which will be fetched via Ajax and then replaced in the target divs.
But before we begin let's learn a bit about Ajax
and JSON
What is Ajax?
Ajax is a client-side script that communicates to and from a server/database without the need for a post back or a complete page refresh. Essentially, Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
What is JSON?
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
How to integrate it with your script?
We will first define a javascript function named update_data()
which fetches the values from the server and then updates the divs with their fetched values.
To do all this, we'll use jQuery as a dependency and will utilize it's jQuery.ajax() method
NOTE - To automatically call the function every second we will also need setInterval method
function update_data() {
$.ajax({
url: 'test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function (data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
Sample PHP script- (test.php)
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$data = Array('time1' => time(), 'time2' => time());
// returns the data with mime type `json` instead of `html`
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data); // converts array into json
}
?>
The above PHP script will return the follwoing JSON
structure:
{
"time1": 'value returned by first call to time()',
"time2": 'value returned by repeated call to time()'
}
Full html example (calls external php)-
<html>
<div id="first">Print some value on page load, will be replaced by Ajax</div>
<div id="second">My dropdown menu goes here</div>
<div id="third">Print some value on page load, will be replaced by Ajax</div>
<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function update_data() {
$.ajax({
url: '/test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function(data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
</script>
</html>
Reference -
1. What does "async: false" do in jQuery.ajax()?