In wordpress we send data using same ajax method as we do in regular non-wordpress website. The difference is few additional data variables and filter on serverside.
To Implement this I created a template page named “Request a Quote” in request-a-quote.php, created new wordpress and assigned that template to this page.
HTML Form:
<form id="request_a_quote" class="col-sm-5" onsubmit="return submit_form()"> <div id="success_msg" class="alert alert-success" style="display:none">Thanks! Your message is sent, we will contact you soon.</div> <h2>Request a Quote</h2> <input type="text" id="name" class="form-control" placeholder="Name" /><br> <input type="text" id="email" class="form-control" placeholder="Email" /><br> <input type="text" id="phone" class="form-control" placeholder="Phone" /><br> <input type="text" id="company_name" class="form-control" placeholder="Company Name" /><br> <textarea id="description" class="form-control" placeholder="Project Description"></textarea><br> <input type="submit" value="Submit" class="btn btn-primary" /> <input type="reset" id="reset" style="display:none" /> </form>
Javascript Code:
function submit_form() { // hide success msg whenever submit is pressed $("#success_msg").fadeOut(); // collectiong data var name = $("#name").val(); var email = $("#email").val(); var phone = $("#phone").val(); var company_name = $("#company_name").val(); var description = $("#description").val(); // Action will be function name which we will create in functions.php var action = "submit_request_a_quote"; // this is required url for ajax calls in the wordpress var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>'; var data = {name:name, email:email, phone:phone, company_name:company_name, description:description, action:action}; $.ajax({ url:ajax_url, type:"POST", data:data }).done(function(responseTxt){ $("#success_msg").fadeIn(); $("#reset").trigger("click"); // clicking reset button to reset form after completion }); return false; }
functions.php
Add following code at the end of functions.php
function submit_request_a_quote() // this is the action data variable we set in ajax { $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $company_name = $_POST['company_name']; $description = $_POST['description']; // preparing parameters for wp_mail(); $to = "[email protected]"; $subject = "New Message from $name"; $msg = " Quote Name: $name Email: $email Phone: $phone Company Name: Project Description: $description "; // sending mail using wp_mail function wp_mail($to, $subject, $msg); wp_die(); // must use wp_die() to avoid unwanted output from wordpress } // in first parameter prefix function name with wp_ajax_ // this action is required in order to recieve data sent from ajax add_action('wp_ajax_submit_request_a_quote', 'submit_request_a_quote');