How to send mail using PHP and Ajax Download

How to send mail using PHP and Ajax, Download Source Code, Live Demo, Responsive and Secure Contact form

In the tutorial, we are going to explain How to send mail using PHP and Ajax.

PHP and AJAX contact form are used to send contact details to the administrator from the back end without contact page refresh. The below contact form form will be very useful to send the mail from your website.

If you are looking PHP, Ajax, Responsive and Secured  contact us form, so Please read the full article. Live Demo and Source Code is available at the bottom.

How to send mail using PHP and Ajax

The HTML code

First, we need to create the contact form using HTML and CSS. The HTML code given below.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Contact Form</title>
<link rel="stylesheet" href="">
body {
    background: #8E0E00;  /* fallback for old browsers */
    background: -webkit-linear-gradient(left, #1F1C18, #8E0E00);
    background: -o-linear-gradient(left, #1F1C18, #8E0E00);
    background: linear-gradient(to right, #1F1C18, #8E0E00);  /* Chrome 10-25, Safari 5.1-6 */ /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
.card {
    border: 0px !important;

<!-- ajax contact form -->
<section style="margin-top: 50px;">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card"> <img src="images/contact-us-form.jpg" /> 
          <div class="card-body">
            <form class="contactForm" method="post" action="sendMail.php">           
              <!-- form message -->
              <div class="row">
                <div class="col-12">
                  <div class="alert alert-success msg" style="display: none" role="alert"> Your message was sent successfully. </div>
              <!-- end message --> 
              <!-- form element -->
              <div class="row">
                <div class="col-md-6 form-group">
                  <input name="fullName" type="text" class="form-control" placeholder="Full Name" required>
                <div class="col-md-6 form-group">
                  <input name="emailId" type="email" class="form-control" placeholder="Email Id" required>
                <div class="col-md-6 form-group">
                  <input name="contactNumber" type="text" class="form-control" placeholder="Contact Number" required>
                <div class="col-md-6 form-group">
                  <input name="subject" type="text" class="form-control" placeholder="Subject" required>
                <div class="col-12 form-group">
                  <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
                <div class="col-12">
                  <input name="submit" type="submit" class="btn btn-success" value="Send Message">
              <!-- end form element -->
<script src=""></script> 
<script src="main.js"></script>

send mail using PHP and Ajax

The Ajax Code

The below Ajax code is used to send the contact information from one page to another without page refresh. The Ajax code given below.

(function ($) {
    'use strict';

    var form = $('.contactForm'),
        message = $('.msg'),

    // Success function
    function done_func(response) {
        setTimeout(function () {
        }, 2000);
        form.find('input:not([type="submit"]), textarea').val('');

    // fail function
    function fail_func(data) {
        setTimeout(function () {
        }, 2000);
    form.submit(function (e) {
        form_data = $(this).serialize();
            type: 'POST',
            url: form.attr('action'),
            data: form_data

The PHP Code

The below PHP code is used to send the mail to the admin.


if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) {

  # FIX: Replace this email with recipient email
  $mail_to = "";

  # Sender Data
  $subject = trim( $_POST[ "subject" ] );
  $fullName = str_replace( array( "\r", "\n" ), array( " ", " " ), strip_tags( trim( $_POST[ "fullName" ] ) ) );
  $emailId = filter_var( trim( $_POST[ "emailId" ] ), FILTER_SANITIZE_EMAIL );
  $contactNumber = trim( $_POST[ "contactNumber" ] );
  $message = trim( $_POST[ "message" ] );

  if ( empty( $fullName )OR!filter_var( $emailId, FILTER_VALIDATE_EMAIL )OR empty( $contactNumber )OR empty( $subject )OR empty( $message ) ) {
    # Set a 400 (bad request) response code and exit.
    http_response_code( 400 );
    echo "Please complete the form and try again.";

  # Mail Content
  $content = '<table width="600" style="border:1px solid #943600; background-color:#F5F5F5" align="center" cellpadding="0" cellspacing="0">
    <td align="center" valign="top"><table width="100%" border="0" cellpadding="4" cellspacing="0">
        <td height="40" colspan="2"  style="font-family:Trebuchet MS; font-size:14px; font-weight:bold; text-transform:uppercase; text-align:center; color:#ffffff; padding: 0px;"><a href="" target="_blank"><img src="" style="width:600px;"></a></td>
        <td colspan="2">&nbsp;</td>
      <tr style="border-bottom:1px solid #ccc;">
        <td width="51%" align="right"><strong>Full Name: </strong></td>
        <td width="49%" align="left"><span style="float:left; width:270px;">' . $fullName . '</span></td>
      <tr style="border-bottom:1px solid #ccc;">
        <td align="right"><strong>Email Id:</strong></td>
        <td align="left"><span style="float:left; width:270px;">' . $emailId . '</span></td>
      <tr style="border-bottom:1px solid #ccc;">
        <td align="right"><STRONG>Contact Number:</STRONG></td>
        <td align="left"><span style="float:left; width:270px;">' . $contactNumber . '</span></td>
	   <tr style="border-bottom:1px solid #ccc;">
        <td align="right"><STRONG><span class="txt4">message</span>:</STRONG></td>
        <td align="left"><span style="float:left; width:270px;">' . $message . '</span></td>

  # email headers.
  $headers = "From: $fullName <$emailId>";
 	//$headers      = "From: $studentname <>\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
    $headers   .= "Content-type: text/html; charset=iso-8859-1\r\n";
  # Send the email.
  $success = mail( $mail_to, $subject, $content, $headers );
  if ( $success ) {
    # Set a 200 (okay) response code.
    http_response_code( 200 );
    echo "Thank You! Your message has been sent.";
  } else {
    # Set a 500 (internal server error) response code.
    http_response_code( 500 );
    echo "Oops! Something went wrong, we couldn't send your message.";

} else {
  # Not a POST request, set a 403 (forbidden) response code.
  http_response_code( 403 );
  echo "There was a problem with your submission, please try again.";



We explained How to send mail using PHP and Ajax. Hope you like it so, Please like and share.

 How to send mail

Read Also: How to display data from database in PHP in table

Read Also: How to make a dependent dropdown list using jquery Ajax Download