Extract more information from PHP pages using JavaScript
P粉445714413
2023-08-13 12:27:33
In order to automatically update a certain part of the page without having to constantly reload the page, I have implemented this code on the platform. If you just want to update a piece of data, everything works fine, in fact the php page contains multiple queries to populate different sections. How do I report the data results for all queries?
This is the JS code in index.php:
<pre class="brush:js;toolbar:false;">function nLettere() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const myObj = JSON.parse(this.responseText);
document.getElementById("nLettere").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "script/caricaNumeri.php", true);
xhttp.send();
}
setInterval(function(){
nLettere();
}, 1);
</pre>
This is the PHP page that sends the query to the database:
<pre class="brush:php;toolbar:false;"><?php
include '../config.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT COUNT(id) AS total FROM indirizzi";
$risultato = $conn->query($query);
if ($risultato->num_rows > 0) {
//output data of each row
while($row = $risultato->fetch_assoc()) {
$numero = $row["totale"];
}
} else {
$numero = "Ancora nessuna per ora!";
}
$query = "SELECT COUNT(stato) AS daConsegnare FROM indirizzi WHERE stato = ''";
$risultato = $conn->query($query);
if ($risultato->num_rows > 0) {
//output data of each row
while($row = $risultato->fetch_assoc()) {
$daConsegnare = $row["daConsegnare"];
}
} else {
$daConsegnare = "Ancora nessuna per ora!";
}
?>
</pre>
Currently this code only works with one piece of data, the result of the first query. But I also need to import the results of the second query and so on...
To update multiple parts of the page with data from different queries, you can modify the JavaScript code and PHP code accordingly. Here's what you can do:
Modify your PHP script (caricaNumeri.php) to return a JSON object containing the results of both queries:
php
Modify your JavaScript code to handle multiple data fragments returned by the PHP script:
javascript
Update your HTML to include a placeholder for the second data:
html
Now when you run the caricaNumeri function it will get the two data fragments from the server and update the corresponding parts of the page. Please adjust the interval (setInterval) according to how often you want the data to be updated.