How can AJAX be utilized to handle form submissions and send emails with PHP in a web development project?

To handle form submissions and send emails with PHP using AJAX in a web development project, you can create a JavaScript function that collects form data, sends it to a PHP script using AJAX, and then have the PHP script process the data and send an email. This allows for a seamless user experience without the need for page reloads.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Send email
    $to = "recipient@example.com";
    $subject = "New message from $name";
    $body = "From: $name\nEmail: $email\nMessage:\n$message";

    if (mail($to, $subject, $body)) {
        echo "Email sent successfully!";
    } else {
        echo "Email sending failed.";
    }
}

?>