After sending mail in php set successful message through ajax

Here is an example of how you can send a mail using PHP and then display a successful message using AJAX:

PHP Code (mail.php)

<?php
// Your mail settings
$to = '[email protected]';
$subject = 'Test Mail';
$message = 'This is a test mail sent using PHP';

// Send the mail
if (mail($to, $subject, $message)) {
    echo 'Mail sent successfully!';
} else {
    echo 'Error sending mail!';
}
?>

HTML Code (index.php)

<form id="mail-form" action="mail.php" method="post">
    <input type="submit" value="Send Mail">
</form>

<div id="mail-message"></div>

<script>
    $(document).ready(function() {
        $('#mail-form').submit(function(event) {
            event.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'mail.php',
                data: $(this).serialize(),
                success: function(response) {
                    $('#mail-message').html(response);
                }
            });
        });
    });
</script>

Explanation

  1. In the PHP code, we have a simple mail function that sends an email to the recipient. If the mail is sent successfully, it echoes a success message.
  2. In the HTML code, we have a form with a submit button. When the form is submitted, we prevent the default form submission behavior using event.preventDefault().
  3. We use jQuery's ajax() method to send a POST request to the PHP file. We serialize the form data using $(this).serialize() and pass it as the data parameter.
  4. In the success callback function, we update the #mail-message div with the response from the PHP file. Since the PHP file echoes a success message, we can display it in the div.

Note: Make sure to replace the mail.php file with your actual PHP file name and path. Also, adjust the mail settings and recipient email address according to your needs.