Build a Contact Us Form using PHP, AJAX and jQuery

The Contact Us form allows users to communicate with web application administrator. It allows them to send queries to the web application owners about relevant services. In this tutorial, we will learn how to Build a Simple Contact Us Form using PHP, AJAX and jQuery. We will cover this tutorial in easy steps with live demo to Contact Us Form in PHP.
So let’s implement Build a Contact Us Form using PHP. look following folder and file structure:
  • build-contact-us-form-using-php-ajax-jquery
    • assets
      • css
        • style.css
      • js
        • ajax.js
    • templates
      • header.php
      • footer.php
    • index.php
    • contactus.php
Step 1: Creating a Simple HTML Contact Form
Now in index.php, we will disign Bootstrap contact form
  

Build a Contact Form using PHP, AJAX and jQuery

Contact Us

We would love to hear from you !

Step 2: Handle jQuery Ajax Contact Form Submit
In ajax.js, we will handle contact form submit with jQuery Ajax to not reload page when submit form. Send Ajax request to contactus.php to send contact page detail email with form validation.
jQuery(document).on('click', 'button#visitor-contact', function(){
    jQuery.ajax({
        type:'POST',
        url:'contactus.php',
        data:jQuery("form#contact-frm").serialize(),
        dataType:'json',    
        beforeSend: function () {
            jQuery('button#visitor-contact').button('loading');
        },
        complete: function () {
            jQuery('button#visitor-contact').button('reset');
            jQuery('#contact-frm').find('textarea, input').each(function () {
                jQuery(this).val('');
            });
            setTimeout(function () {
                jQuery('span#sent-msg').html('');
            }, 7000);
        },                
        success: function (json) {
           jQuery('.text-danger').remove();
            if (json['error']) {
             
                for (i in json['error']) {

                  var element = jQuery('.input-contact-' + i.replace('_', '-'));
                  if (jQuery(element).parent().hasClass('input-group')) {
                       
                    jQuery(element).parent().after('
' + json['error'][i] + '
'); } else { jQuery(element).after('
' + json['error'][i] + '
'); } } } else { if(json.type=='message') { jQuery('span#sent-msg').html('
Success!'+json.text+'
'); } else { jQuery('span#sent-msg').html('
Error! '+json.text+'
'); } } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); });
Step 3: Send Contact Form Details
Now finally in contactus.php, User fill the conatct us form and clicks on send button, following php code will executes.
\r\n";
    $mailBody = "Visitor Name: " . $first_name .' '. $last_name . "\n";
    $mailBody .= "Visitor Email: " . $email . "\n";
    $mailBody .= "Visitor comment: " . $comment . "\n";

    if (mail($toEmail, "Contact Mail", $mailBody, $mailHeaders)) {
        echo $json = json_encode(array('type'=>'message', 'text' => 'Hi '.$first_name .', thank you for the comments. We will get back to you shortly.'));
    } else {
        echo $json = json_encode(array('type'=>'error', 'text' => 'Unable to send email, please contact '.$toEmail));
    }
} else {
    echo json_encode($json);
}

// email validation
 function validateEmail($email) {
    return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE;
}
?>
Create header.php and footer.php section of the webpage. The Bootstrap and jQuery library is used to provide a better UI, so, include it in the header and footer section.
header.php



  
    
  
  
  
  
  
  
  
  
  Build a Contact Form using PHP, AJAX and jQuery | Web Haunt
  
  
  
  
  
  
  
   
   


  
  	
footer.php