Not sure why this isn’t working… my action is being passed and the right function is firing from my ajax, but the callback isn’t receiving my query
parameter.
My ajax (using bloodhound.js running from the administrative screens, so no need to localize
):
new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: ajaxurl,
prepare: function(query,settings){
settings.url = settings.url + '?query=' + query + '&action=' + 'find_posts'
return settings;
}
}
})
If you’re not familiar with Bloodhound, the query it renders looks like this:
admin-ajax.php?query=fdsafpasdjflkdsajkfg&action=find_posts
Here fdsafpasdjflkdsajkfg
is just the search string I typed in (in frustration 😢). So I know it is sending the correct query strings, and I also know because the error I get stems from the right action being fired.
My error is
PHP Fatal error: Call to a member function esc_like() on null
It stems from this:
add_action( 'wp_ajax_find_posts', 'find_posts' );
function find_posts(){
$query = $_GET['query'];
$value="%".$wpdb->esc_like($query).'%'; //ERROR HERE
$sql = $wpdb->prepare("SELECT ID, post_title
FROM {$wpdb->prefix}posts
WHERE post_title LIKE %s
ORDERBY BY ID", $value);
$posts = $wpdb->get_results($sql);
return json_encode($posts);
wp_die();
}
So the question is, why is $_GET['query'];
resolving to null
when it is in my query string?
1 Answer
Add global $wpdb;
in function find_posts()
, before you use $wpdb
;