<div class="checker-tag">
<h2>Form Title</h2>
</div>
<div class="col-md-6">
<form id="theForm" name="pc" method="post">
<input type="text" id="pc" name="postalcode" placeholder="Enter your postcode" value="">
<!----- the_ajax_hook is name of action ---->
<input name="action" type="hidden" value="the_ajax_hook" />
<button type="button" name="submit" class="btn btn-default hvr-sweep-to-right" onClick="submit_me();">Submit</button>
</form>
</div>
<!------ Response will display here -------->
<div id="response_area" class="col-md-6"></div>
Use admin-ajax.php file to call ajax
function js_enqueue_scripts() {
wp_register_script("my-ajax-handle", plugin_dir_url(__FILE__) . "ajax.js", array('jquery'));
wp_enqueue_script("my-ajax-handle");
//the_ajax_script will use to print admin-ajax url in custom ajax.js
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");
Now, execute function
function the_action_function() {
global $wpdb;
$pc = $_POST['postalcode'];
$sql = "SELECT * FROM `postcodes` INNER JOIN authorities WHERE `postcode` LIKE '$pc'";
$results = $wpdb->get_results($sql);
foreach ($results as $row) {
//Execute Code Here
}
}
// the_ajax_hook is now use here
add_action('wp_ajax_the_ajax_hook', 'the_action_function');
add_action('wp_ajax_nopriv_the_ajax_hook', 'the_action_function'); // need this to serve non logged in users
Now, Add js in ajax.js file
function submit_me() {
jQuery("#loader").show(); //It will show loader div
jQuery.post(the_ajax_script.ajaxurl,
jQuery("#theForm").serialize(),
function (response_from_the_action_function) {
jQuery("#loader").hide();
if (response_from_the_action_function == '') {
alert('Please check your postcode.It may be wrong or incorrect.');
}
else {
jQuery("#response_area").html(response_from_the_action_function);
}
}
);
}
You can use also below format for js
jQuery('#theForm').on('submit', function (e) {
jQuery('body').addClass('loading');
e.preventDefault();
var formdata = jQuery("#theForm").serialize() + "&action=" + 'the_ajax_hook';
jQuery.ajax({
url: the_ajax_script.ajax_url,
type: 'post',
data: formdata,
success: function (response) {
jQuery('body').removeClass('loading');
if (response == 1) {
jQuery("#response_area").html(response_from_the_action_function);
}
}
});
return false;
});