What is the purpose of using setInterval() in PHP with AJAX and JavaScript?
When using AJAX in PHP with JavaScript, setInterval() can be used to periodically send requests to the server for updated data without the need for manual user interaction. This can be useful for real-time updates on a webpage or for fetching new information from the server at regular intervals.
<script>
setInterval(function(){
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it to make a GET request to a PHP file on the server
xhr.open('GET', 'update_data.php', true);
// Send the request
xhr.send();
// Define what to do when the response is received
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
// Update the webpage with the new data received from the server
document.getElementById('data').innerHTML = xhr.responseText;
}
}
}, 5000); // Send request every 5 seconds
</script>
Keywords
Related Questions
- How can the current Y position, string height, and page height be utilized to prevent page breaks within table cells when generating PDFs using TCPDF in PHP?
- What alternative approach was suggested using Domdoc for editing HTML?
- What are some best practices for implementing configuration classes in PHP projects?