WordPress Reservation Form Plugin Using by Ajax

You need to create a PHP file in plugin directory and copy below the snippets

<?php
/*
Plugin Name: Ajax Reservation Form
Plugin URI: http://example.com
Description: Reservation Form
Version: 1.0
Author: Ataur Rahman
Author URI: md-ataur.github.io
License: GPL v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: ajaxrf
*/

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

if(!class_exists('AjaxReservationForm')){

	class AjaxReservationForm{

		public function __construct(){
			add_action('plugins_loaded', array($this, 'ajaxrf_load_textdomain' ));
			add_action('wp_enqueue_scripts', array($this, 'ajaxrf_enqueue_scripts'));
			add_shortcode( 'ajax_reservation_form', array($this,'ajaxrf_shortcode' ));
			add_action( 'wp_ajax_ajaxRSF', array($this, 'AjaxdataProcess') );
			add_action( 'wp_ajax_nopriv_ajaxRSF', array($this, 'AjaxdataProcess') );
		}
		public function ajaxrf_load_textdomain(){
			load_plugin_textdomain( 'ajaxrf', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
		}
		public function ajaxrf_enqueue_scripts(){
			wp_enqueue_style( 'bootstrap', plugin_dir_url( __FILE__ ).'assets/public/css/bootstrap.min.css');
			wp_enqueue_script( 'ajax-reservation-js', plugin_dir_url( __FILE__ ).'assets/public/js/ajax-reservation.js', array( 'jquery' ), time(), true );
			$ajaxUrl = admin_url( 'admin-ajax.php');
			wp_localize_script( 'ajax-reservation-js', 'url', array('ajaxUrl' => $ajaxUrl) );
		}

		public static function AjaxdataProcess(){
			if (check_ajax_referer( 'rsf_nonce_action', 'rn', false )) {
				$name 	= sanitize_text_field( isset($_POST['RFname'])?$_POST['RFname']:'' );
				$email 	= sanitize_email( isset($_POST['RFemail'])?$_POST['RFemail']:'' );
				$phone 	= sanitize_text_field( isset($_POST['RFphone'])?$_POST['RFphone']:'' );
				$person = sanitize_text_field( isset($_POST['RFperson'])?$_POST['RFperson']:'' );
				$date 	= sanitize_text_field( isset($_POST['RFdate'])?$_POST['RFdate']:'' );
				$time 	= sanitize_text_field( isset($_POST['RFtime'])?$_POST['RFtime']:'' );
				$message 	= sanitize_text_field( isset($_POST['RFMessage'])?$_POST['RFMessage']:'' );
				if (!empty($name) && !empty($email) && !empty($phone) && !empty($person) && !empty($date) && !empty($time)) {					
					$email_message = wp_sprintf( "From: %s \nEmail: %s \nPhone: %s \nPersons: %s \nTime: %s \nMessage: %s", $name , $email, $phone, $person, $time, $message);		
					//$admin_email = get_option('admin_email');			
					wp_mail( 'contact@onlivetech.com', $name, $email_message );
					die ('<p class="alert alert-success">Successfully sent your reservation</p>');
				}else{
					die('<p class="alert alert-danger">Fields must no be empty</p>');
				}
			}
		}

		public static function ajax_reservation_form(){			
			?>
			<div class="container">
				<div class="col-md-6 offset-md-3">
					<div id="msg"></div>
	                <form action="<?php the_permalink(); ?>" id="Rform">
	                	<?php wp_nonce_field( 'rsf_nonce_action', 'rsf_nonce_field');?>
                        <div class="form-group">
                            <label for="name" class="label"><?php _e('Name','ajaxrf');?></label>
                            <input type="text" class="form-control" id="RFname">                            
                        </div>
                        <div class="form-group">
                            <label for="email" class="label"><?php _e('Email','ajaxrf');?></label>
                            <input type="email" class="form-control" id="RFemail">                           
                        </div>
                        <div class="form-group">
                            <label for="phone" class="label"><?php _e('Phone','ajaxrf');?></label>
                            <input type="text" class="form-control" id="RFphone">
                        </div>
                        <div class="form-group">
                            <label for="persons" class="label"><?php _e('Number of Persons','ajaxrf');?></label>
                            <select name="persons" id="RFperson" class="form-control">
                                <option value="1"><?php _e('1 person','ajaxrf');?> </option>
                                <option value="2"><?php _e('2 person','ajaxrf');?> </option>
                                <option value="3"><?php _e('3 person','ajaxrf');?></option>
                                <option value="4"><?php _e('4 person','ajaxrf');?></option>
                                <option value="5"><?php _e('5 person','ajaxrf');?></option>
                            </select>                            
                        </div>
                        <div class="row">
	                        <div class="form-group col-md-6">
	                            <label for="date" class="label"><?php _e('Date','ajaxrf');?></label>
	                            <input type="date" class="form-control" id="RFdate">	                            
	                        </div>
	                        <div class="form-group col-md-6">
	                            <label for="time" class="label"><?php _e('Time','ajaxrf');?></label>
	                            <input type="time" class="form-control" id="RFtime" autocomplete="off">
	                        </div>
                        </div>	 
                        <div class="form-group">
                        	<textarea class="form-control" id="RFMessage" rows="5"></textarea>
                        </div>                 
	                    <div class="row justify-content-center">
	                    	<button id="reserveForm" class="btn btn-primary"><?php _e('Reserve Now','ajaxrf');?></button>
	                    </div>
	                </form>
	            </div>
			</div>
			<?php
		}

		public function ajaxrf_shortcode(){
			// Turn on output buffering.
    		ob_start();

			self::ajax_reservation_form(); // echo the form

			// Turn off output buffering and then return the output echoed via the above functions.
    		return ob_get_clean();
		}
	}
	
	new AjaxReservationForm;
}

You need to create a js file and copy below the snippets

;(function($){
	$(document).ready(function(){		
		$('#reserveForm').on('click', function(){
			$.post(url.ajaxUrl, {
				action: 'ajaxRSF',
				rn: $('#rsf_nonce_field').val(),
				RFname: $('#RFname').val(),
				RFemail: $('#RFemail').val(),
				RFphone: $('#RFphone').val(),
				RFperson: $('#RFperson').val(),
				RFdate: $('#RFdate').val(),
				RFtime: $('#RFtime').val(),
				RFMessage: $('#RFMessage').val()
			}, function(data) {
				$('#msg').html(data);
				console.log(data);
				$('#Rform')[0].reset();
			});			
			return false;
		});
	});
})(jQuery);

Build Your Own WordPress Contact Form Using by Ajax

You need to create a template file and copy below the snippets

<?php
/**
 * Template Name: Ajax Contact Form
 */
get_header();
?>

<div class="container">
	<div class="col-md-6 offset-md-3">	
		<form action="<?php the_permalink(); ?>" method="post" id="cform">
			<?php wp_nonce_field('cf_nonce_action','cf_nonce_field'); ?>
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group">
						<label for="firstName"><?php _e("First Name","practice");?></label>
						<input type="text" class="form-control" id="firstName">
					</div>
				</div>
				<div class="col-sm-6">
					<div class="form-group">
						<label for="lastName"><?php _e("Last Name","practice");?></label>
						<input type="text" class="form-control" id="lastName">
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group">
						<label for="subject"><?php _e("Subject","practice");?></label>
						<input type="text" class="form-control" id="subject">
					</div>
				</div>
				<div class="col-sm-6">
					<div class="form-group">
						<label for="phone"><?php _e("Phone","practice");?></label>
						<input type="text" class="form-control" id="phone" >
					</div>
				</div>
			</div>
			<div class="form-group">
				<label for="email"><?php _e("Email Address","practice");?></label>
				<input type="email" class="form-control" id="email">
			</div>
			<div class="form-group">
				<label for="message"><?php _e("Message","practice");?></label>
				<textarea class="form-control" id="message" rows="5"></textarea>
			</div>
			<button type="submit" id="ajaxForm" class="btn btn-primary btn-block"><i class="fa fa-paper-plane"></i> <?php _e("Send Message","practice")?></button>
		</form>
	</div>
</div>

<?php get_footer();?>

Then you need to create a js file and copy below the snippets

;(function($){
	$(document).ready(function(){		
		$('#ajaxForm').on('click',function(){
			$.post(cfurl.ajaxurl,{
				action: 'ajaxContactForm',
				nonce: $('#cf_nonce_field').val(),
				firstName: $('#firstName').val(),
				lastName: $('#lastName').val(),
				subject: $('#subject').val(),
				phone: $('#phone').val(),
				email: $('#email').val(),
				message: $('#message').val(),
			}, function(data){
				alert(data);
				console.log(data);
				$("#cform")[0].reset();
			});			
			return false;
		});
	});
})(jQuery);

What we did on the js file.
First of all, question yourself what would you do. I would like to send user data to the WordPress or php by the form click event without page relode. We created a click event and then sent user data by jQuery post function.

Functions.php file

/**
 * Enqueue scripts and styles.
 */
function practice_scripts() {
	wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/public/css/bootstrap.min.css');		
	
	if (is_page_template('templates/ajax-contact-form.php')) {
		wp_enqueue_script( 'ajax-cf-js', get_template_directory_uri() . '/assets/public/js/ajax-contact-form.js', array( 'jquery' ), time(), true );
	}	

	$ajaxurl = admin_url('admin-ajax.php');	
	wp_localize_script( 'ajax-cf-js', 'cfurl', array('ajaxurl' => $ajaxurl) );

}
add_action( 'wp_enqueue_scripts', 'practice_scripts' );


/**
 * Ajax Contact Form
 */
function practice_ajaxContactForm(){	
	if(check_ajax_referer('cf_nonce_action', 'nonce')){
		$firstName = sanitize_text_field( isset($_POST['firstName'])?$_POST['firstName']:'' );
		$lastName = sanitize_text_field( isset($_POST['lastName'])?$_POST['lastName']:'' );
		$subject = sanitize_text_field( isset($_POST['subject'])?$_POST['subject']:'' );
		$phone = sanitize_text_field( isset($_POST['phone'])?$_POST['phone']:'' );
		$email = sanitize_email( isset($_POST['email'])?$_POST['email']:'' );
		$message = esc_textarea( isset($_POST['message'])?$_POST['message']:'' );
		if (!empty($firstName) && !empty($lastName) && !empty($subject) && !empty($phone) && !empty($email) && !empty($message)) {
			$_message = sprintf("From: %s \nEmail: %s \nPhone: %s \nMessage: %s", $firstName, $email, $phone, $message  );
			$admin_email = get_option('admin_email');		
			wp_mail( $admin_email, $subject, $_message );
			die('Successfully Message Sent');
		}else{
			die('Fields must not be empty!');
		}				
	}
}
add_action('wp_ajax_ajaxContactForm', 'practice_ajaxContactForm'); // Logged in
add_action('wp_ajax_nopriv_ajaxContactForm', 'practice_ajaxContactForm'); // Not Logged in