How to send mail using ajax in php
To send a mail using AJAX in PHP, you'll need to make an AJAX request to a PHP script that handles the mail sending. Here's a step-by-step guide:
Step 1: Create a PHP script to handle the mail sending
Create a new PHP file, e.g., sendmail.php
, and add the following code:
<?php
// Configuration
$to = '[email protected]';
$subject = 'Test Mail';
$message = 'This is a test mail sent using AJAX';
// Set the mail headers
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: text/plain; charset=UTF-8';
// Send the mail using PHP's mail function
if (mail($to, $subject, $message, $headers)) {
echo 'Mail sent successfully!';
} else {
echo 'Error sending mail!';
}
?>
Step 2: Create an AJAX request to send the mail
In your HTML file, create a form with a submit button. When the button is clicked, use JavaScript to send an AJAX request to the sendmail.php
script:
<form id="mail-form">
<input type="text" id="recipient-email" placeholder="Recipient's email">
<input type="text" id="subject" placeholder="Subject">
<textarea id="message" placeholder="Message"></textarea>
<button id="send-mail">Send Mail</button>
</form>
<script>
document.getElementById('send-mail').addEventListener('click', function() {
var recipientEmail = document.getElementById('recipient-email').value;
var subject = document.getElementById('subject').value;
var message = document.getElementById('message').value;
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set the request method and URL
xhr.open('POST', 'sendmail.php', true);
// Set the request headers
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Send the request
xhr.send('recipientEmail=' + recipientEmail + '&subject=' + subject + '&message=' + message);
});
</script>
Step 3: Handle the AJAX request in PHP
In your sendmail.php
script, use the $_POST
superglobal to retrieve the form data sent by the AJAX request:
<?php
// Retrieve the form data
$recipientEmail = $_POST['recipientEmail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Send the mail using PHP's mail function
if (mail($recipientEmail, $subject, $message)) {
echo 'Mail sent successfully!';
} else {
echo 'Error sending mail!';
}
?>
That's it!
When the user clicks the "Send Mail" button, the AJAX request will be sent to the sendmail.php
script, which will send the mail using PHP's mail
function. The response from the PHP script will be displayed in the browser.
Note: Make sure to replace the placeholders ($to
, $subject
, $message
, etc.) with your actual mail configuration and form data.