I am currently using a WP_Query
that'll trigger from an AJAX call when a button is pressed. The post meta fields lat
lng
will be used as location data for a google map. The query outputs fine without AJAX but cannot seem to get it to return the results with it.
The response I receive - [{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]
Now I believe the error is when transforming the results into JSON at json_encode
stage, but not too sure? Any help would be great, fairly new to AJAX!
Function.php
<?php
//Search Function
function ek_search(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date'],
'post_type' => 'property',
'posts_per_page' => 20,
'date_query' => array(
array(
'after' => $_POST['property_added']
),
),
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
$locations[] = array(
"name" => get_the_title(),
"lng" => get_field('loc_lng'),
"lat" => get_field('loc_lat')
);
}
$location = json_encode($locations);
echo $location;
die();
}
add_action( 'wp_ajax_nopriv_ek_search', 'ek_search' );
add_action( 'wp_ajax_ek_search', 'ek_search' );
Form
<form id="filter">
<button>Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
JS
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: "ek_search"};
$.ajax({
url: ajaxurl,
data:data,
type: 'post',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
return false;
});
});