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;
});
});
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;
});
});
Share
Improve this question
edited Jul 2, 2017 at 20:00
Johansson
15.4k11 gold badges44 silver badges80 bronze badges
asked Jul 2, 2017 at 17:19
scopeakscopeak
2131 gold badge5 silver badges15 bronze badges
1
- Have you considered using a REST API endpoint instead? You wouldn't even need to json encode, echo and call die, it's all taken care of for you – Tom J Nowell ♦ Commented Jul 2, 2017 at 22:00
3 Answers
Reset to default 6Admin-AJAX is not optimized for JSON. If you need your answer to be in JSON, use the REST-API instead. This API generates JSON response by default.
All you have to do is to register a rest route, and access the URL:
add_action( 'rest_api_init', function () {
//Path to REST route and the callback function
register_rest_route( 'scopeak/v2', '/my_request/', array(
'methods' => 'POST',
'callback' => 'my_json_response'
) );
});
Now, the callback function:
function my_json_response(){
$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 );
if($query->have_posts()){
while($query->have_posts()){
$query->the_post();
$locations[]['name'] = get_the_title();
$locations[]['lat'] = get_field('loc_lng');
$locations[]['lng'] = get_field('loc_lat');
}
}
//Return the data
return $locations;
}
Now, you can get your JSON response by visiting the following URL:
wp-json/scopeak/v2/my_json_response/
For testing purposes, you can change POST
method to GET
and directly access this URL. If you get a response, then change it back to POST
and work on your javascript.
That's all.
First of all, how are you getting the $_POST
variables? you have to pass them in your data
object on your ajax call. Example:
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: 'ek_search', date: date, property_added: property};
$.ajax({
url: ajaxurl,
data:data,
type: 'post',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
return false;
});
});
See this Article for reference.
Firstly, I am really sorry for responding a little late.
Second, you need to get the values of your form by using the serialize method, Please check the below example.
<form id="filter">
<input type="button" name="smt" value="Submit" id="smt" />
<input type="hidden" name="action" value="ek_search">
</form>
<script src="http://ajax.googleapis/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#filter");
$("#smt").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>