In WordPress it little bit complicated then default way to handle ajax. Modify your js code like this.
function ajaxSubmit(e){
// prevent the default action.
e.preventDefault();
var myform= jQuery(this).serialize();
jQuery.ajax({
type:"POST",
// Get the admin ajax url which we have passed through wp_localize_script().
url: ajax_object.ajax_url,
action: "submitAjaxForm",
data: myform,
success:function(data){
jQuery(".records").html(data);
}
});
return false;
}
In above JS code I have replaced the form url and added action parameter. Wordpress gives us a unified file to use that is admin-ajax.php. It is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
Why form url replaced with ajax_object.ajax_url ?
This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
Define form action.
To define the form action, we need to add these action using wp_ajax_
and wp_ajax_nopriv_
as prefix. With callback function to handle those form data.
Example.
add_action('wp_ajax_{YourFormAction}','{CallbackFunction}');`
add_action('wp_ajax_nopriv_{YourFormAction}','{CallbackFunction}');
Add this code to functions.php
file
add_action('init', 'registerFormAction');
function registerFormAction(){
// To handle the form data we will have to register ajax action.
add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback');
add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback');
}
Handle ajax form data
Put your all code which is going to handle the form data, Inside the callback function which we have recently hooked with the wp_ajax_{yourAction}
above.
function submitAjaxForm_callback(){
if (isset($_POST['store_list']) && $_POST['store_list'] != 'Select by Store'){
$store_list = $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list . "' AND code IN ('test3') ORDER BY street ASC", OBJECT));
foreach ($stores as $record_s){
echo '<div class="records">';
echo '<div><span>' . $record_s->malls . '</span></div>';
echo '</div>';
}
} elseif (isset($_POST['street_list']) && $_POST['street_list'] != 'Select by'){
$street_list = $_POST['street_list'];
$streets = $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE street_list= '" . $street_list. "' AND code IN ('test3') ORDER BY stores ASC", OBJECT));
foreach ($streets as $record_m){
echo '<div class="records">';
echo '<div><span>' . $record_m->stores . '</span></div>';
echo '</div>';
}
}
// It is necessary to terminate the get proper data.
wp_die();
}