How can AJAX or Websockets be used in PHP to display a loading graphic while waiting for API data?
When making API calls in PHP, the page may take some time to load the data, causing a delay in displaying the content. To address this issue, you can use AJAX or Websockets to asynchronously fetch the data while displaying a loading graphic to indicate to the user that the request is being processed.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$('#loading').show();
$.ajax({
url: 'api_endpoint.php',
type: 'GET',
success: function(data) {
$('#loading').hide();
$('#content').html(data);
}
});
});
</script>
</head>
<body>
<div id="loading" style="display: none;">Loading...</div>
<div id="content"></div>
</body>
</html>
Keywords
Related Questions
- How can PHP developers efficiently show and hide elements using jQuery for a better user experience?
- How can one troubleshoot a "Forbidden" error message when accessing a file generated by PHP on a local Xampp server?
- How can the $_SERVER['HTTP_HOST'] variable affect the execution of the "header" function in PHP?