Passing JSON data from WP Query into AJAX causing NULL errors

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.

Leave a Comment