Bootstrap 5 Contact Form with Jquery and PHP
December 30, 2022
We are creating a simple HTML form with Bootstrap 5 and using simple jquery validation with Ajax. It has name, phone, email and message fields. We have included HTML, Jquery and PHP code with this article.
HTML code
Copy
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Bootstrap 5 contact form</title> </head> <body> <div class="container"> <div class="row"> <div class="col-lg-4 offset-lg-4 col-md-6 offset-md-3 mt-5"> <h2 class="mb-3">Contact Form</h2> <form id="contact-form" method="post" action="contact.php" role="form"> <div class="form-group mb-3"> <label for="form_name" class="form-label">Name</label> <input id="form_name" type="text" name="name" class="form-control" placeholder="Name" required> <div class="form-feedback"></div> </div> <div class="form-group mb-3"> <label for="form_phone" class="form-label">Phone</label> <input id="form_phone" type="text" name="phone" class="form-control" placeholder="Phone" required data-error="Phone is required."> <div class="form-feedback"></div> </div> <div class="form-group mb-3"> <label for="form_email" class="form-label">Email</label> <input id="form_email" type="email" name="email" class="form-control" placeholder="Email address" required data-error="Valid email is required."> <div class="form-feedback with-errors"></div> </div> <div class="form-group mb-3"> <label for="form_message" class="form-label">Your Message</label> <textarea id="form_message" name="message" class="form-control" placeholder="Your Message" rows="2" required data-error="Please, leave us a message."></textarea> <div class="form-feedback with-errors"></div> </div> <div class="messages"></div> <button type="submit" class="btn btn-primary w-100 mt-2" type="button" disabled>Submit</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="contact.js"></script> </body> </html>
contact.js - Include Jquery Validation and Ajax
Copy
$(function() { $('#contact-form')[0].reset(); var n = false, p = false, e = false, m = false; var validateActive = 1; activeButton(0); var formName = '#form_name:required', formPhone = '#form_phone:required', formEmail = '#form_email:required', formMassage = '#form_message:required', nameValidate = '^[a-z A-Z]{3,16}$', phoneValidate = '^[0-9]{10,16}$', emailValidate = '^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$'; $(formName).on("input blur", function() { var massage = $(this).parent().find('.form-feedback'); if ( $(this).val().length != 0) { if ( $(this).val().match(nameValidate) ) { $(this).addClass('is-valid').removeClass('is-invalid'); $(massage).text(" "); n = true; } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text('Please provide a valid name'); n = false; } } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text("Name is required"); n = false; } activeButton(validateActive); }); $(formPhone).on("input blur", function() { var massage = $(this).parent().find('.form-feedback'); if ( $(this).val().length != 0) { if ( $(this).val().match(phoneValidate) ) { $(this).addClass('is-valid').removeClass('is-invalid'); $(massage).text(" "); p = true; } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text('Please provide a valid phone'); p = false; } } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text("Phone is required"); p = false; } activeButton(validateActive); }); $(formEmail).on("input blur", function() { var massage = $(this).parent().find('.form-feedback'); if ( $(this).val().length != 0) { if ( $(this).val().match(emailValidate) ) { $(this).addClass('is-valid').removeClass('is-invalid'); $(massage).text(" "); e = true; } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text('Please provide a valid email'); e = false; } } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text("Email is required"); e = false; } activeButton(validateActive); }); $(formMassage).on("input blur", function() { var massage = $(this).parent().find('.form-feedback'); if ( $(this).val().length != 0) { $(this).addClass('is-valid').removeClass('is-invalid'); $(massage).text(" "); m = true; } else { $(this).addClass('is-invalid').removeClass('is-valid'); $(massage).addClass('invalid-feedback').text("Massage is required"); m = false; } activeButton(validateActive); }); function activeButton(a) { if((n && p && e && m == true) && a == 1) { $('.btn').removeAttr('disabled'); } else { $('.btn').attr('disabled', true); } } $('#contact-form').submit(function(event) { $('#contact-form .btn').attr("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'); $('#contact-form .form-control').attr('readonly', true); validateActive = 0; event.preventDefault(); $.ajax({ url: 'contact.php', type: 'post', data: $('#contact-form').serialize(), dataType: 'json', success: function(data) { var messageAlert = data.type; var messageText = data.message; var alertBox = '<div class="alert alert-' + messageAlert + ' alert-dismissible fade show" role="alert">' + messageText + '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>'; if (messageAlert && messageText) { $('#contact-form .form-control').removeClass('is-valid'); $('#contact-form .btn').attr("disabled", false).html('Submit'); $('#contact-form .form-control').attr('readonly', false); $('.btn').prop('disabled', true); $('#contact-form').find('.messages').html(alertBox); $('#contact-form')[0].reset(); validateActive = 1; n = false, p = false, e = false, m = false; }; setTimeout(function() { $('#contact-form .messages > div').remove(); }, 3000); } }); }); });
contact.php
Copy
<?php if (isset($_POST["name"])){ $successMessage = 'Contact form successfully submitted.'; $errorMessage = 'There was an error while submitting the form. Please try again later'; $user_name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; $email_from = $email; $email_subject = 'Website Contact From - '.$user_name; $email_body = ' <div style="background-color:#fafafa;"> <div style="padding:20px;font-size:14px;color:#888;"> <span style="font-size:20px;color:#2b2b2b;">'.$user_name.'</span> <br> Email: <span style="color:##3f5dd0">'.$email.'</span> <br> Phone: <span style="color:##3f5dd0">'.$phone.'</span> <br> <br> Message: <div style="color:#2b2b2b">'.$message.'</div> </div> </div>'; $to_email = "example@example.com"; //replace 'TO MAIL ID' hear $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $email \r\n". "MIME-Version: 1.0\r\n" . "Content-Type: text/html; charset=UTF-8"; if(!mail($to_email,$email_subject,$email_body,$headers)){ $responseArray = array('type' => 'danger', 'message' => $errorMessage); } else { $responseArray = array('type' => 'success', 'message' => $successMessage); } } if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $encoded = json_encode($responseArray); header('Content-Type: application/json'); echo $encoded; } else { echo $responseArray['message']; } ?>