How can a form in a PHP file be evaluated without calling a "new" page?

To evaluate a form in a PHP file without calling a "new" page, you can use AJAX to submit the form data asynchronously to the same PHP file and handle the form submission without refreshing the page. This allows you to process the form data in the background and update the page dynamically based on the response from the server.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data here
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Return a response
    echo "Form submitted successfully!";
    exit;
}
?>

<form id="myForm">
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var formData = new FormData(this);
    
    fetch(window.location.href, {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        alert(data); // Display the response message
    });
});
</script>