In this lecture, We will talk about form, building our custom ajax form, submitting forms, sending form data, processing data, form messages, and success messages.
Form Enquiry
First, we will create a form without an action attribute because we will do this with jQuery later.
<form id="enquiry"> <div class=" row"> <input class="col-md-6 mb-2" type="text" name="fname" placeholder="First name"> <input class="col-md-6 mb-2" type="email" name="email" placeholder="Email"> <input class="col-md-6 mb-2" type="text" name="phone" placeholder="Phone"> <input class="col-md-6 mb-2" type="textarea" name="textarea"> <button type="submit">Submit</button> </div> </form>
We created a simple form above, now it’s time to send data from the form by using jQuery and Ajax.
jQuery Script
Add the below script after the form
<script> $ = jQuery; $('#enquiry').submit( function(event){ event.preventDefault(); var endpoint = '<?php echo admin_url('admin-ajax.php'); ?>'; var form = $('#enquiry').serialize(); var formdata = new FormData; formdata.append('action','enquiry'); formdata.append('enquiry',form); $.ajax(endpoint,{ type: 'POST', data:formdata, processData: false, contentType: false, success:function(res){ $('#enquiry').fadeOut(200); $('#success_message').text('Thanks for yur enquiry').show(); }, error:function(err){ } }) } ); </script>
If you got an error about jQuery not being found, so migrate jquery by enqueuing it in functions.php file.
wp_enqueue_script('jquery');
Now it’s time to send data, use below sending method in functions.php file.
add_action('wp_ajax_enquiry','enquiry_form'); add_action('wp_ajax_nopriv_enquiry','enquiry_form'); function enquiry_form(){ $formdata = [ ]; wp_parse_str($_POST['enquiry'], $formdata); // Admin Email $admin_email = get_option('admin_email'); //Email Headers $headers[ ] = 'Content-Type: text/html; charset=UTF-8'; $headers[ ] = 'Form:' . $admin_email; $headers[ ] = 'Reply-to: ' . $formdata [ 'email ' ]; // Who are we sending the email to? $send_to = $admin_email; //Subject $subject = "Enquiry form " . $formdata[ 'fname' ] . ' ' . $formdata[ 'phone']; //Message $message = ' '; foreach($formdata as $field){ $message .= '<strong>' . $index . '</strong>: ' . $field . '<br/>'; } try{ if(wp_mail($send_to, $subject, $message, $headers)){ wp_send_json_success( ' Email Sent' ); } else{ wp_send_json_success( ' Email Error' ); } } catch (Exception $e){ wp_send_json_error($e->getMessage()); } wp_send_json_success( $formdata['fname'] ); }
If you get email’s on junk and spam don’t worry about it, we will setup SMTP for this.
#BeingCodeStuffer