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.";
}
}
?>
Keywords
Related Questions
- What is the common issue with placing HTML tags before and after an img tag in PHP?
- What are the best practices for handling inconsistent string formats when using PHP functions like preg_replace() for pattern matching?
- How can the fopen() function be used to overwrite the contents of a text file in PHP?