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">
<head>
<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="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<style>
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;
}
</style>
</head>
<body>

<!-- 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>
                </div>
              </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>
                <div class="col-md-6 form-group">
                  <input name="emailId" type="email" class="form-control" placeholder="Email Id" required>
                </div>
                <div class="col-md-6 form-group">
                  <input name="contactNumber" type="text" class="form-control" placeholder="Contact Number" required>
                </div>
                <div class="col-md-6 form-group">
                  <input name="subject" type="text" class="form-control" placeholder="Subject" required>
                </div>
                <div class="col-12 form-group">
                  <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
                </div>
                <div class="col-12">
                  <input name="submit" type="submit" class="btn btn-success" value="Send Message">
                </div>
              </div>
              <!-- end form element -->
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
<script src="main.js"></script>
</body>
</html>

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'),
        form_data;

    // Success function
    function done_func(response) {
        message.fadeIn().removeClass('alert-danger').addClass('alert-success');
        message.text(response);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
        form.find('input:not([type="submit"]), textarea').val('');
    }

    // fail function
    function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-success');
        message.text(data.responseText);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
    }
    
    form.submit(function (e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form_data
        })
        .done(done_func)
        .fail(fail_func);
    });
    
})(jQuery);

The PHP Code

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

<?php

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

  # FIX: Replace this email with recipient email
  $mail_to = "test9889@gmail.com";

  # 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.";
    exit;
  }

  # Mail Content
  $content = '<table width="600" style="border:1px solid #943600; background-color:#F5F5F5" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td align="center" valign="top"><table width="100%" border="0" cellpadding="4" cellspacing="0">
       
      <tr>
        <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="https://htmlcss3tutorials.com/" target="_blank"><img src="https://htmlcss3tutorials.com/wp-content/uploads/images/advertisment-banner.webp" style="width:600px;"></a></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
        </tr>
      <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>  
      <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>
      <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>
   
	   <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>
      </tr>   
</table>';

  # email headers.
  $headers = "From: $fullName <$emailId>";
 	//$headers      = "From: $studentname <info@ggspindia.com>\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.";
}

?>

Conclusion

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