Use Ajax in WordPress custom template or theme.
View/Template (HTML & jQuery)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <div id="vp-form"> <div id="feedback"></div> <form type="post" action="" id="customTailoringForm" accept-charset="multipart/form-data" enctype="multipart/form-data"> <label for="name">Name:</label> <input name="name" type="text" /> <label for="email">Email:</label> <input name="email" type="text" /> <label for="phone">Phone:</label> <input name="phone" type="text" /> <label for="address">Address:</label> <input name="address" type="text" /> <input type="hidden" name="action" value="addCustomTailoring"/> <input type="submit"> </form> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script type="text/javascript"> jQuery('#customTailoringForm').submit(ajaxSubmit); function ajaxSubmit() { var customTailoringForm = jQuery(this).serialize(); jQuery.ajax({ type: "POST", url: "/vipul/wordpress/wp-admin/admin-ajax.php", data: customTailoringForm, success: function(data){ jQuery("#feedback").html(data); } }); return false; } </script> |
admin-ajax.php is fix file from wordpress, all ajax request will go to ‘admin-ajax.php’ , and request will work in ‘function.php’ as given below.
function.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | wp_enqueue_script('jquery'); function addCustomTailoring() { global $wpdb; $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $address = $_POST['address']; if ( $wpdb->insert( 'custom_tailoring', array( 'name' => $name, 'email' => $email, 'address' => $address, 'phone' => $phone ) ) === false ) { echo 'Error'; } else { echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id; } die(); } add_action('wp_ajax_addCustomTailoring', 'addCustomTailoring'); add_action('wp_ajax_nopriv_addCustomTailoring', 'addCustomTailoring'); |