Can’t use get_results() in ajax query

I’m using a jquery ajax call to get certain data from wpdb and I’m getting the following message:

<b>Fatal error</b>:  Call to a member function get_results() on a non-object in <b>C:\wamp\www\maps_en2\markers.php</b> on line <b>15</b><br />

This is the call:

$.ajax({
    type: "POST",
    url: "markers.php",
    data: ({'southWestLat' : southWestLat , 'southWestLng' : southWestLng , 'northEastLat' : northEastLat , 'northEastLng' : northEastLng}),
    success: function(msg){
    alert( msg );
    }
});

And this is the called code – markers.php:

<?php
    global $wpdb;
    $sql = "SELECT user_id, lat, lng FROM coordinates WHERE lat>".$_POST["southWestLat"]." and lat<".$_POST["northEastLat"]." and lng>".$_POST["southWestLng"]." and lng<".$_POST["northEastLng"];
    $rows = $wpdb->get_results($sql, OBJECT_K);
    ...
?>

What’s strange is that when the php code was on the same file as the javascript (and instead of the parameters ‘southWestLat’ etc, I used numbers, then it worked.
I should state that the jquery is in a php file under twentyten theme folder but markers.php is under the root directory (couldn’t use it when it was in the theme for some reason).

1 Answer
1

This will not work because you call example.com/markers.php directly, and that file does not load anything from WordPress, like the $wpdb object.

You can include wp-load.php, but this might break if you move the WordPress installation to somewhere else. To be more in line with how Ajax calls in WordPress should be made, you should write it as a hook for wp_ajax_[action]. See my introduction to Ajax in WordPress for more details.

Leave a Comment