πHow To Make Working Contact Form With JavaScript
The steps to create a simple HTML JavaScript contact form:
HTML Structure:
Create an HTML file (e.g.,
contact.html
) with a basic structure:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form</title>
</head>
<body>
<!--form here -->
<form id="contact-form" method="POST" action="sendmail.php">
<div class="form-row form-error" style="display:none;"></div>
<div class="form-row">
<label for="contact-form-name">Name:</label>
<input id="contact-form-name" class="form-input" type="text" name="name" required>
</div>
<div class="form-row">
<label for="contact-form-email">Email:</label>
<input id="contact-form-email" class="form-input" type="email" name="email" required>
</div>
<div class="form-row">
<label for="contact-form-phone">Phone:</label>
<input id="contact-form-phone" class="form-input" type="tel" name="phone">
</div>
<div class="form-row">
<label for="contact-form-message">Message:</label>
<textarea id="contact-form-message" class="form-input" name="message" required></textarea>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
CSS Styling:
Add CSS code to the
<head>
tag to style the form:
.form-row {
margin-bottom: 10px;
}
.form-input {
display: block;
}
.form-error {
color: red;
}
Server-Side Processing (PHP):
Create a PHP file (e.g.,
sendmail.php
) to handle form data processing.In
sendmail.php
, check if the request method is POST and validate the required form variables (name, email, and message).If all variables are present, use the data to send an email:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$to = "[email protected]"; // Replace with your email address
$subject = "New Contact Form Submission";
$body = "Name: {$name}\nEmail: {$email}\nPhone: {$phone}\nMessage: {$message}";
// Use PHP mail() function to send the email
mail($to, $subject, $body);
}
}
?>
Remember to replace "[email protected]"
with your actual email address.
Conclusion: Follow these steps to create a functional contact form using HTML, JavaScript, and PHP. π§
PreviousHow to automate sending daily email reports in Python, and how I would set it up.NextHow to Create a header line that appears when a user scrolls using HTML, CSS, and JavaScript
Last updated