Load Ajax data before results load
-
Hi All,
I have issue with ajax in my site.
In theme folder created one file called archive-doctors.php
In this page displaying all doctors created in admin. The doctor has custom taxonomies called location and specialty.So in front-end showing these dependent taxonomy select box filters.
Up to here fine. Now I want get current location(by asking users to allow current location) and show that location results only and in location filter select box set this value.To do this I used googlemaps api to get current location.And sending this location value to php by using ajax.
JS in archive-doctors.php
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script> <script type="text/javascript"> var loc = ''; var ploc = ''; if(!!navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(position) { var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'location': {lat:position.coords.latitude,lng:position.coords.longitude}}, function(results, status){ if (status === 'OK'){ if(results[0]){ loc = results[0].address_components[2].long_name; ploc = results[0].address_components[3].long_name; } } var data = { 'action': 'sf_get_current_loc', 'ploc': ploc, 'loc':loc }; jQuery.ajax({ type:'post', data:{action:'sf_get_current_loc','ploc': ploc,'loc':loc}, url:ajaxurl, success: function(data){} }); }); }); } </script>
functions.php
add_action( 'wp_ajax_nopriv_sf_get_current_loc','sf_get_current_loc'); add_action( 'wp_ajax_sf_get_current_loc','sf_get_current_loc'); function sf_get_current_loc(){ $my_query = new WP_Query( array('cur_loc' => $_POST['loc'],'cur_ploc' => wp_die(); }
Now I am using pre_get_posts action to get above set values to filter result by post__in
add_action('pre_get_posts', 'cur_location_filter'); function cur_location_filter($query) { $post_ids = get post id by location if (!is_admin() && $query->is_main_query()) { $query->set('post__in', array($post_ids)); } }
But here first pre_get_posts loaded and then ajax function loading.So in query loc and ploc is not available
How to load ajax as first request of page ? Please help
- The topic ‘Load Ajax data before results load’ is closed to new replies.