Passing JSON data from WP Query into AJAX causing NULL errors

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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="https://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>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x