How can PHP and JavaScript be integrated to display a loading GIF during form processing?

To display a loading GIF during form processing, you can use JavaScript to show the loading GIF when the form is submitted, and PHP to process the form data. By combining these two languages, you can create a seamless user experience where the loading GIF is displayed while the form is being processed in the background.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data here

    // Display loading GIF while processing
    echo '<script type="text/javascript">
            document.getElementById("loading").style.display = "block";
          </script>';

    // Simulate processing time
    sleep(2); // 2 seconds

    // Hide loading GIF after processing is complete
    echo '<script type="text/javascript">
            document.getElementById("loading").style.display = "none";
          </script>';
}
?>