A simple example of AJAX for an HTML form
As they say, a developer does not live by WordPress alone. Today I will show an example of AJAX for a simple landing page built without the most popular CMS. The form sends an email without a page reload.
Problem: We need a simple HTML form that sends emails to our mailbox, without WordPress, only clean HTML, PHP and jQuery.
Solution: We will use three files:
- index.html with the page content (the .php extension instead of .html works too);
- mail.php with the code that sends the email;
- script.js with the JavaScript.
NOTE: In addition, there are the jQuery library and the styles file, which I put into the js and css folders.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HelloAdmin Example</title>
<link rel="stylesheet" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js" defer></script>
<script src="js/script.js" defer></script>
</head>
<body>
<form action="mail.php" class="contact-form" method="post">
<h1>Lorem ipsum dolor sit amet</h1>
<div class="flex">
<div class="input">
<input type="text" name="name" placeholder="Name*" class="input-field" required>
</div>
<div class="input">
<input type="email" name="email" placeholder="Email*" class="input-field" required>
</div>
</div>
<div class="flex">
<div class="input">
<input type="text" name="campus" placeholder="Campus*" class="input-field" required>
</div>
<div class="input">
<input type="tel" name="phone" placeholder="Phone" class="input-field">
</div>
</div>
<div class="input">
<textarea name="message" rows="10" placeholder="Tell us a bit about yourself..." class="input-field"></textarea>
</div>
<button type="submit" class="btn">Submit</button>
</form>
</body>
</html>
The action="mail.php" means that the form still works if JavaScript is disabled, just with a page reload.
mail.php
The required attributes check the fields in the browser, but anyone can send a request to mail.php directly, so the script checks them too. It is a few lines, and without them the form quickly becomes a source of spam.
<?php
$to = 'admin@yourdomain.com'; // your email address
$from = 'info@yourdomain.com'; // the sender address, a mailbox on your domain
$name = trim( strip_tags( $_POST['name'] ?? '' ) );
$email = trim( $_POST['email'] ?? '' );
$campus = trim( strip_tags( $_POST['campus'] ?? '' ) );
$phone = trim( strip_tags( $_POST['phone'] ?? '' ) );
$message = trim( strip_tags( $_POST['message'] ?? '' ) );
if ( $name === '' || $campus === '' || ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
echo "<div class='error'>Please fill in all required fields.</div>";
exit;
}
$subject = 'Message from HelloAdmin site';
$body = "Hello! Somebody sent the contact form on your site.\n\n"
. "Name: $name\n\nEmail: $email\n\nCampus: $campus\n\nPhone: $phone\n\nMessage: $message";
$headers = "From: $from\r\nReply-To: $email\r\nContent-Type: text/plain; charset=utf-8";
if ( mail( $to, $subject, $body, $headers ) ) {
echo "<div class='success'>Mail sent. Thank you, " . htmlspecialchars( $name ) . ", we will contact you shortly.</div>";
} else {
echo "<div class='error'>Error. Please try again.</div>";
}
Reply-To lets you answer the visitor with the “Reply” button. The From address should be on your own domain, otherwise many mail servers mark the message as spam.
My first version also sent a copy of the message to the visitor’s address. I removed it: such a form lets anyone send emails from your server to any address.
script.js
jQuery( function ( $ ) {
var form = $( '.contact-form' );
form.on( 'submit', function ( e ) {
e.preventDefault();
$.ajax( {
type: 'post',
url: form.attr( 'action' ),
data: form.serialize(),
success: function ( data ) {
form.trigger( 'reset' );
$( data ).appendTo( form );
setTimeout( function () {
form.find( '.success, .error' ).fadeOut( 300, function () {
$( this ).remove();
} );
}, 5000 );
},
error: function () {
$( "<div class='error'>Error. Please try again.</div>" ).appendTo( form );
}
} );
} );
} );
Sources: