What is the purpose of using AJAX in PHP for form submission on dynamically loaded pages?

When submitting forms on dynamically loaded pages, traditional form submission can cause the entire page to reload, disrupting the user experience. Using AJAX in PHP allows for asynchronous form submission, where only the form data is sent to the server without reloading the entire page. This results in a smoother and more seamless user interaction.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data here
    
    // Return a response (e.g. success or error message)
    echo json_encode(["message" => "Form submitted successfully"]);
    exit;
}
?>