2

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;
    });
});
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 3

6

Admin-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.

8
  • Thanks for the more up to date API approach, definitely want to use this method! I got a response ok but still displaying null in the fields. If I use that exact query within the page template it outputs the JSON fine so not sure what's causing it still. Any ideas?
    – scopeak
    Commented Jul 2, 2017 at 21:49
  • @scopeak You're welcome. Admin-AJAX comes in handy when you need to echo your content for some reason, otherwise REST is more efficient. Have you tried and accessing the URL directly? If you get an answer this way, then the problem is with the jQuery AJAX. Please let me know about this.
    – Johansson
    Commented Jul 2, 2017 at 21:52
  • Yep, sorry I've accessed the URL directly with wp-json/scopeak/v2/my_request using the identical code you provided. And it spits out the usual [{"name":""},{"lat":null},{"lng":null},]
    – scopeak
    Commented Jul 2, 2017 at 21:57
  • @JackJohansson you shouldn't use POST or GET directly in a REST callback, you should use the request object passed as a parameter to the callback instead
    – Tom J Nowell
    Commented Jul 2, 2017 at 22:01
  • 1
    Dang! That's it :) Thanks guys can't believe I missed that I used foreach instead of while Now onto the AJAX, will mark as solved for now. Thanks!
    – scopeak
    Commented Jul 2, 2017 at 22:05
1

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.

3
  • I had tried to do data = { action: 'ek_search', name: name, lat: lat, lng: lng}; but spat out an error saying lat doesn't exist. Is that correct to reference the $_POST variables?
    – scopeak
    Commented Jul 2, 2017 at 21:22
  • You have to pass trough the data object any values that you will use in the action. In your code you're trying to get two parameters in the $_POST, the $_POST['date'] and $_POST['property_added'], you have to pass them trough the ajax call. Commented Jul 2, 2017 at 21:30
  • I updated my answer with a post showing an example. Commented Jul 2, 2017 at 21:40
0

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.com/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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.