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>