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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s