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 Send Email from localhost in PHP using SMTP. 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.


	// 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.


<!Doctype html>
<html lang="en">
  <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="">
  <script src=""></script>
  <script src=""></script>
<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>
        <form id="contactForm">
          <div class="form-group">
             <input type="text" class="form-control" name="name" placeholder="Name" required="">
          <div class="form-group">
             <input type="email" class="form-control" name="email" placeholder="Email" required="">
          <div class="form-group">
             <input type="text" class="form-control" name="subject" placeholder="Subject" required="">
          <div class="form-group">
             <input type="file" class="form-control" name="attachment" required="">
          <div class="form-group">
             <textarea rows="5" class="form-control" name="message" placeholder="Message" required=""></textarea>
          <div class="form-group">
            <button type="submit" class="btn btn-primary btn btn-block" id="btnSubmit">Send Message</button>

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">
      $("#btnSubmit").text('Please wait..');
      $("#btnSubmit").prop("disabled", true);

      var formdata = new FormData(this);  
        url  : "contacts_form.php",
        type : "POST",
        data :formdata,
          $("#success").text("Contact form submitted successfully");
          $("#btnSubmit").text('Send Message');
          $("#btnSubmit").prop("disabled", false);

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.


	// Include database connection file


	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) 
	    $result = mysqli_query($con, $query);

	   if ($result==true) {
	        sendMail($email, ucwords($subject),$message);
	       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 = '';   				        // Specify main and backup SMTP servers
		$mail->SMTPAuth = true;                                 // Enable SMTP authentication
		$mail->Username = '';                // 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('', 'Your Name');  // Add a recipient
		$mail->addAddress('');    		    // 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;



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 or problems about this tutorial, please comment on the form below.😊

Contact form send attachment using jquery ajax in PHP


Leave a Reply

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

  1. I’ve mentioned some sites below that are accepting guest posts,I would appreciate it if you would see them out and then, after you have done so, let me know which of these sites you would like to post on.
    If you are interested in any of these sites.

    • Yes, I am accept top three of these website for guest posts. after some time i will accept all of these site for guest posts.

      And this is my email id you can send me email for more discussion.