Contact form send attachment using jquery ajax in PHP

In this Post we will see how to create a contact form send attachment with using jquery Ajax and PHP and also Insert contact form data in database table.

Using a contact form with attachments, users can send a contact information file to a support person or administrator. This is enhanced by allowing multiple attachments via the contact form. Some of my readers want to post code for this.

If you are looking for a How to configure SMTP server to Send Email using PHP ?. In this post I have explain step by step to send email from localhost using PHPMailer file with SMTP.

In this tutorial we look at an example program for email attachments to a contact form. We use PHPMailer via SMTP to send email. In the previous tutorial we saw PHP code to send email from contact form via PHP and jQuery without attachments.

In this example I’ve displayed an HTML contact form for getting user details with attachments, if any. After submitting this form, the input field values ​​will be sent to the PHP email script via AJAX. The PHP code processes the script to send a letter with attachments and send the response to AJAX.

Created Database Configuration File

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create dbconfig.php file on your root directory and put bellow code:

If you want to save contact form details in database table So, that you need to create a database file and include our project.

dbconfig.php

<?php
	// Database configuration 
	$dbHost     = "localhost"; 
	$dbUsername = "root"; 
	$dbPassword = ""; 
	$dbName     = "registration"; 
	 
	// Create database connection 
	$con = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	}
?>

Create Contact Form with Attachment File

This HTML code is used to display the contact form fields to users who wish to submit requests via this form. This form contains data for entering name, email, subject, message and attachments.

All fields are required on this form. So add javascript validation to check the opacity of all fields and validate the email using regex. This validation script is called when this form is submitted.

index.php

<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact form send attachment using jquery ajax in PHP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:50px">
<h1 style="text-align:center;">Contact form send attachment using jquery ajax in PHP</h1><br>
  <div class="row">
    <div class="col-md-3"></div>
      <div class="col-md-6">
        
        <div class="alert alert-success alert-dismissible success" style="display: none;">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <span id="success"></span>
        </div>
        
        <form id="contactForm">
          <div class="form-group">
             <input type="text" class="form-control" name="name" placeholder="Name" required="">
          </div>
          <div class="form-group">
             <input type="email" class="form-control" name="email" placeholder="Email" required="">
          </div>
          <div class="form-group">
             <input type="text" class="form-control" name="subject" placeholder="Subject" required="">
          </div>
          <div class="form-group">
             <input type="file" class="form-control" name="attachment" required="">
          </div>
          <div class="form-group">
             <textarea rows="5" class="form-control" name="message" placeholder="Message" required=""></textarea>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary btn btn-block" id="btnSubmit">Send Message</button>
          </div>  
        </form>
      </div>
    </div>
  </div>
</body>
</html>

jQuery AJAX Contact form Mail Sending script with attachment File

After submitting the contact form, the following jQuery script sends an AJAX call request to the PHP script and sends data from the contact form. If successful, the AJAX response confirms the email delivery status to the user.

<script type="text/javascript">
  $(document).ready(function(){
    $("#contactForm").on("submit",function(e){
      e.preventDefault();
      $("#btnSubmit").text('Please wait..');
      $("#btnSubmit").prop("disabled", true);

      var formdata = new FormData(this);  
      
      $.ajax({
        url  : "contacts_form.php",
        type : "POST",
        cache:false,
        data :formdata,
        contentType:false,
        processData:false,
        success:function(response){
          $("#success").text("Contact form submitted successfully");
          $(".success").show();
          $("#btnSubmit").text('Send Message');
          $("#btnSubmit").prop("disabled", false);
          $("#contactForm").trigger('reset');
        },
      });
    });
  });
</script>

Create PHP code sending contact Mail with attachment

On this page we create PHP code to send data to database tables and we also send HTML emails from localhost to PHP using PHPMailer. Download the PHPMailer file from Github.

If you want to learn Send email from localhost using PHPMailer with SMTP. In this post I explain step by step.

contact_form.php

<?php
	// Include database connection file

	include_once('config.php');

	if (isset($_POST['email'])) {

	    $name = strip_tags(trim($_POST["name"]));
	    $name = str_replace(array("\r","\n"),array(" "," "), $name);
	    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
	    $subject = trim($_POST["subject"]);
	    $message = trim($_POST["message"]);
	    $attachement = $_FILES["attachment"]['name'];

	    $query = "INSERT INTO contacts (name, email, subject, message, attachement) 
		      VALUES('$name','$email','$subject','$message','$attachement')";
		
	    $result = mysqli_query($con, $query);

	   if ($result==true) {
	        sendMail($email, ucwords($subject),$message);
	   }else{
	       return false;
	   }	
	}


	// Create PHPMailder function for sent mail

	function sendMail($to, $subject, $message){
		
		require 'PHPMailer/PHPMailerAutoload.php';

		$mail = new PHPMailer(true);
		$mail->SMTPDebug = 3;                                   // Enable verbose debug output
		$mail->isSMTP();                                        // Set mailer to use SMTP
		$mail->Host = 'smtp.gmail.com';   				        // Specify main and backup SMTP servers
		$mail->SMTPAuth = true;                                 // Enable SMTP authentication
		$mail->Username = 'youremail@gmail.com';                // SMTP username
		$mail->Password = 'yourpassword';                       // SMTP password
		$mail->SMTPSecure = 'tls';                              // Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;                                      // TCP port to connect to
		$mail->setFrom($to, 'Contact us');
		$mail->addAddress('youremail@gmail.com', 'Your Name');  // Add a recipient
		$mail->addAddress('youremail@gmail.com');    		    // Name is optional
		$mail->addReplyTo($to, 'Contact us');
		$mail->isHTML(true);                                    // Set email format to HTML
		$mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']); // Add attachments

		$mail->SMTPOptions = array(
			'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
			)
		);                    
		
		$mail->Subject = $subject;
		$mail->Body    = $message;
		
		if($mail->send()) {
		   return true; 
		} else {
		   return false;
		}
	}

?>

Output

Contact form send attachment using jquery ajax in PHP

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the form below.😊

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *