Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
thanks for the detailed answer but it's way out of my league. I have to take the wp-load.php approach for now and I'll write a memo to deal with it when the installation is moved. I would appreciate it if you can further help despite of taking the less favored approach. I've edited my question and added the results with that include. –  Ash May 30 '11 at 14:12
    
@Ash: No problem. What is this header.php file you are trying to load? Can you update the question with the complete file? Or come to the chat room, then we can discuss it in detail there. –  Jan Fabry May 30 '11 at 14:18
    
I included header.php by mistake. Probably, looking at some example. I've now changed it to wp-load.php and everything's working! thanks a lot. –  Ash May 30 '11 at 14:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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